首页 > 解决方案 > Python 3.7:通过 python 套接字发送文件时出错

问题描述

使用 Python,我想将数据发布到套接字。
我用 Python 3.7 编写了一个客户端/服务器程序,通过网络发送一个大的 csv 文件。客户端和服务器代码如下。

示例文件:

$ cat datafile.csv
id,first_name,gender,car,money,city,country,jobtitle
1,Marline,Female,Ford,$4.94,Kanzaki,Japan,Food Chemist
2,Ker,Male,Lincoln,$3.46,Fort Beaufort,South Africa,Marketing Manager
3,Wallie,Male,Land Rover,$5.12,Eystur,Faroe Islands,Senior Quality Engineer
4,Deonne,Female,Ford,$9.72,Fontaínhas,Portugal,Social Worker
5,Barnaby,Male,Volkswagen,$0.60,Taoyuan,China,Web Developer I
6,Maximilian,Male,GMC,$1.19,Nowy Dwór Gdański,Poland,Engineer IV
7,Wake,Male,Buick,$5.08,Kazuno,Japan,Food Chemist
8,Truman,Male,Infiniti,$1.60,Içara,Brazil,Senior Quality Engineer
9,Mufi,Female,Ford,$7.55,Gununglajang,Indonesia,Actuary
10,Dniren,Female,Ford,$7.71,Yuyapichis,Peru,Software Consultant

下面是客户端服务器程序:

客户端代码:

$ cat client.py

import socket

HOST = 'server ip'        # The remote host
PORT = 42050              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
f = open('/home/vijee/data/datafile.csv', 'rb')
print "Sending Data ...."  
l = f.read()
while True:      
    for line in l:
        s.send(line)    
    break
f.close()
print "Sending Complete"
s.close()

服务器代码:

$ cat server.py

import socket

HOST = 'local ip'         # server ip
PORT = 42050              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
print "Server running", HOST, PORT
s.listen(5)
conn, addr = s.accept()
print'Connected by', addr

while True:
    data = "".join(iter(lambda:conn.recv(1),"\n"))       
    print data   
    if not data: break                

print "Done Receiving"
conn.close()

在执行 client.py 脚本时,我收到以下错误:

bash_shell:~$ python /home/vijee/data/python_code/server.py 
Server running localhost 9000
Connected by ('127.0.0.1', 42950)

bash_shell:~$ python /home/vijee/data/python_code/client.py 
Sending Data ....
Traceback (most recent call last):
  File "/home/vijee/data/python_code/client.py", line 12, in <module>
    s.send(line)    
TypeError: a bytes-like object is required, not 'int'

我知道这是一个小错误。但无法找到错误。

标签: pythonpython-3.xsocketsclient-server

解决方案


l是一个bytes对象。从文档中:

虽然 bytes 文字和表示基于 ASCII 文本,但 bytes 对象实际上表现得像不可变的整数序列

因此,当您编写 时for line in l:, 的每个值line都是一个包含文件中单个字节的整数。参数gs.send()必须是bytes,而不是整数。所以你可以使用:

s.send(bytes([line]))

将整数转换为bytes对象。不要忘记[]--bytes构造函数需要一个序列。如果你只是 write bytes(line),它将创建一个bytes长度为line且内容都是零字节的对象。

尝试一次发送一个字节的循环实际上没有任何理由。只需使用

s.send(l)

一次性发送。

顺便说一句,变量名称line表明您认为您正在逐行发送,而不是逐字节发送。那没有发生。由于您以二进制模式打开文件,因此它没有行的概念。即使您以文本模式打开它,它l也是一个字符串,而不是行序列;如果您想要一系列行,您应该使用f.readlines(), 或for line in f:.


推荐阅读