尝试使用套接字发送pickle数据后出现TypeError

时间:2014-10-02 15:42:49

标签: python image sockets python-2.7 pickle

我试图将图像从服务器发送到客户端,所以我认为我会使用pickle来序列化图像。

服务器的代码:

import socket
import cPickle as pickle

server_socket = socket.socket()
server_socket.bind(('127.0.0.1', 1729))

server_socket.listen(1)
(client_socket, client_address) = server_socket.accept()

client_request = client_socket.recv(1024)

if client_request == 'IMG':
    img_data =  actions.options[client_request]()
    client_socket.send(pickle.dump(img_data, -1))
else:
    client_socket.send(actions.options[client_request]())

server_socket.close()

但是当我尝试运行它时(在检查img_data是否正确创建后),我收到错误:

File "C:/py_prog/my_server.py", line 25, in <module> client_socket.send(pickle.dump(img_data, -1)) TypeError: argument must have 'write' attribute

如何更改要编写的pickle数据的属性?

1 个答案:

答案 0 :(得分:3)

要获取pickle字符串,您应该使用pickle.dumps,而不是pickle.dump(它接受第二个参数的类文件对象)

>>> import cPickle as pickle
>>> pickle.dump('not a real image data', -1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument must have 'write' attribute
>>> pickle.dumps('not a real image data', -1)
'\x80\x02U\x15not a real image dataq\x01.'

client_socket.send(pickle.dumps(img_data, -1))
                              ^