glarkou
glarkou

Reputation: 7101

Send an image through socket as binary data

I have a multithreaded echo server:

from socket import *
import threading
import thread

def handler(clientsock,addr):
    while 1:
        data = clientsock.recv(BUFSIZ)
        if not data:
            break
        msg = 'echoed:... ' + data
        clientsock.send(msg)
     clientsock.close()

if __name__=='__main__':
    HOST = 'localhost'
    PORT = 21567
    BUFSIZ = 1024
    ADDR = (HOST, PORT)
    serversock = socket(AF_INET, SOCK_STREAM)
    serversock.bind(ADDR)
    serversock.listen(2)

    while 1:
        print 'waiting for connection...'
        clientsock, addr = serversock.accept()
        print '...connected from:', addr
        thread.start_new_thread(handler, (clientsock, addr))

I would like to convert the server in order to return an binary image instead of the original message and modify the client accordingly.

Can someone point me an example?

Upvotes: 0

Views: 5128

Answers (1)

Jeremy Roman
Jeremy Roman

Reputation: 16355

If you have the image data in a string, you can just replace your call to clientsock.send(msg) with clientsock.sendall(image_data). You can just read the image data out of a file using something along the lines of:

image = open('my_image.jpg', 'rb')
image_data = image.read()
image.close()

Upvotes: 2

Related Questions