使用套接字

时间:2018-05-24 22:02:47

标签: arrays python-2.7 csv sockets stream

我正在尝试从服务器向客户端发送列表。 列表看起来像这样(它是一个csv文件)。

201,8,0040000080
205,8,1f421d25721e

但发送时我收到此错误:

TypeError: must be string or buffer, not lis

我尝试了两个选项:

  1. 遍历列表并将每个字符串发送到服务器,但结果是这样:

    201 ---> 2,0,1

  2. 尝试投射每一行,例如str(line),然后发送它,但得到了这个:

    201,8,0040000080 ---> [,',2,0,1,',“,”,,',8,',“,”,,',0,0,4,0,0,0,0,0,8,0, ”]

  3. 我该如何解决这个问题?我只是想将数据从客户端发送到服务器。对于记录,客户端代码:

        import socket
        import csv
    
        clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    
        with open('can_data.csv', 'rb') as csv_file:
            csv_reader = csv.reader(csv_file)
            for line in csv_reader:
                    clientSock.sendto(str(line), (self.address, self.port))
    

    服务器代码:

          with open('output.csv', 'wb') as new_file:
            csv_writer = csv.writer(new_file)
    
            while True:
                data, addr = s.recvfrom(1024)
                csv_writer.writerow(data)
    

1 个答案:

答案 0 :(得分:0)

双方需要就序列化格式达成一致。与str(line)配对时,ast.literaleval()可能有效,但repr(line)会更好,repr会尝试更精确地表示str。您还可以转到序列化协议,例如picklejson

假设这是python 3,我还将csv移动到文本并在线路上使用了utf-8编码。

客户端:

import socket
import csv

address = 'localhost'
port = 5555

clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
with open('can_data.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    for line in csv_reader:
        clientSock.sendto(repr(line).encode('utf-8'), (address, port))

服务器:

import socket
import csv
import ast

address = 'localhost'
port = 5555

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((address, port))

with open('output.csv', 'w') as new_file:
    csv_writer = csv.writer(new_file)

    while True:
        data, addr = sock.recvfrom(1024)
        csv_writer.writerow(ast.literal_eval(data.decode('utf-8')))