将pickle数据发送到服务器

时间:2016-06-25 13:31:43

标签: python sockets server network-programming pickle

我想向服务器发送几条腌制消息。使用socket.makefile()我将套接字转换为类文件对象并生成pickle.load(文件)数据。当客户端套接字关闭时,服务器应该接收空字节字符串(无)并关闭其套接字。我面临的问题是服务器中的这一行引发EOFError: Ran out of inputmessage = pickle.load(file) 在Python中文件的结尾只是一个空字符串吗?

import socket, pickle, argparse, sys

def server(interface, port):
    '''Server that waits for a pickled string'''
    sock = socket.socket(type=socket.SOCK_STREAM)
    sock.bind((interface, port))
    print('Server bound to', sock.getsockname())
    sock.listen(1)
    print('Run this script in another window with "-c" to connect')
    sc, sockname = sock.accept()
    print('Accepted connection from', sockname)
    sc.shutdown(socket.SHUT_WR)
    file = sc.makefile(mode='rb')
    while True:
        message = pickle.load(file)
        if not message:
            print('Received zero bytes')
            break
        print('Server received:', repr(message))
    sc.close()
    sock.close()
    print('Server socket closed')

def client(hostname, port):
    '''Client that sends a pickled string'''
    sock = socket.socket(type=socket.SOCK_STREAM)
    sock.connect((hostname, port))
    sock.shutdown(socket.SHUT_RD)
    print('Client at', sock.getsockname())
    sock.sendall(pickle.dumps('Hello, World!'))
    sock.sendall(pickle.dumps('Bye, Bye, People!'))
    sock.sendall(pickle.dumps('It was nice knowing you'))
    sock.close()
    print('Client socket closed')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Send and receive pickled data')
    parser.add_argument('-hostname', default='127.0.0.1', help='IP address or hostname')
    parser.add_argument('-c', action='store_true', help='run as the client')
    parser.add_argument('-p', default=1060, type=int, help='port number')
    args = parser.parse_args()
    function = client if args.c else server
    function(args.hostname, args.p)

0 个答案:

没有答案