通过套接字将图像作为二进制数据发送

时间:2012-02-09 17:34:32

标签: python sockets python-3.x

我有一个多线程的echo服务器:

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))

我想转换服务器以返回二进制映像而不是原始消息,并相应地修改客户端。

有人可以给我一个例子吗?

1 个答案:

答案 0 :(得分:2)

如果您将图片数据包含在字符串中,则可以将clientsock.send(msg)的来电替换为clientsock.sendall(image_data)。您可以使用以下内容从文件中读取图像数据:

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