如何通过python发送对象?

时间:2014-12-18 08:49:04

标签: python sockets object

我有一台服务器:

import socket
import time
import random
from PIL import ImageGrab

server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.bind(('127.0.0.1',8820))
server_socket.listen(1)

while True:
    print "Waiting for commands"
    a = ImageGrab.grab()
    CommandDict = {"TIME" : time.strftime("%a %b %d %H:%M:%S %Y"),"NAME": "Ori","RANDOM":   str(random.randint(0,10)),"EXIT":"BYE","PRINT SCREEN":a}
    (client_socket, client_address) = server_socket.accept()
    client_data = client_socket.recv(1024)
    print "GOT COMMAND FROM " + client_address[0] + " : " + client_data
    client_socket.send(CommandDict[client_data])
    client_socket.close()

server_socket.close()

和客户:

import socket
from PIL import ImageGrab
while True:
    client_input = raw_input("Enter You Command: ")
    CommandList=["EXIT","TIME","NAME","RANDOM","PRINT SCREEN"]
    if client_input in CommandList:
        my_socket=socket.socket()
        my_socket.connect(('127.0.0.1',8820))
        my_socket.send(client_input)
        data = my_socket.recv(1024) + "\n"
        if client_input=="PRINT SCREEN":
        data.save()
        else:
            print "SERVER: " + data
    else: 
        print "Invalid command. try one of those: " + " , ".join(CommandList) + "\n" + "."


my_socket.close()

当我尝试这个时它会给我一个错误,因为它试图将它作为一个字符串对象发送。 我想通过套接字发送一个对象,我希望客户端读取它。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

Python包含一个名为pickle的对象序列化模块:https://docs.python.org/2/library/pickle.html

您可以使用pickle.dumps(CommandDict[client_data])生成一个字符串,然后您可以在套接字上发送该字符串。然后使用pickle.loads恢复另一侧的对象。当然,这要求对象是可选择的,但是许多简单的数据结构都是,或者可以毫无困难地制作。在您的情况下,您可能需要添加一些代码来挑选ImageGrab对象类型,但首先尝试它并查看它是否默认工作。

答案 1 :(得分:1)

以下应该允许您挑选图像。我目前的机器上没有PIL,所以我还没有能够正确测试它。机器

import cPickle as pickle # cPickle is considerably more efficient than pickle
import copy_reg
from StringIO import StringIO
from PIL import Image, ImageGrab

def pickle_image(img):
    """Turns an image into a data stream. Only required on machine sending the 
    image."""
    data = StringIO()
    img.save(data, 'png')
    data.seek(0)
    return unpickle_image, (data,)

def unpickle_image(data):
   """Turns a data stream into an image. Required on both machines"""
    img = Image.open(data)
    data.close() # releases internal buffer immediately
    return img

# tells pickle it should use the function pickle_image to pickle objects of 
# type Image. Required on the machine sending the image
copy_reg.pickle(Image, pickle_image)

some_image = ImageGrab.grab()
# HIGHEST_PROTOCOL uses a more effcient representation of the object
pickled_image = pickle.dumps(some_image, pickle.HIGHEST_PROTOCOL)

unpickled_image = pickle.loads(pickled_image)

在我的代码中,我使用dumpsloads来创建和使用数据的字符串表示。理想情况下,您应该使用dumpload,并将my_socket.makefile()作为文件参数传递。