我正在尝试通过套接字发送/接收数据。将字符串转换为整数值时出现此错误。这个整数值是文件名的长度。
Traceback (most recent call last):
File "C:\Users\Nitesh Rathi\Desktop\clientSocket.py", line 16, in <module>
buff = int(filesize)
ValueError: invalid literal for int() with base 10: ''
代码
发送方
from socket import *
import os
HOST = '192.168.1.7'
PORT = 9999
ADDRESS = (HOST, PORT)
soc = socket(AF_INET, SOCK_STREAM)
soc.bind(ADDRESS)
soc.listen(5)
print('listen for connection...')
conn, addr = soc.accept()
print('got connection from', addr)
filename = 'file1.txt'.encode('utf-8')
fl = len(filename)
fl = str(fl)
print('size of filename :', fl, 'bytes')
conn.send(fl.encode('utf-8'))
print('size of filename sent')
conn.send(filename)
print('filename sent')
filedata = 'this is file1 data'.encode('utf-8')
conn.sendall(filedata)
print('data sent')
conn.close()
soc.close()
print('socket closed')
接收方
from socket import *
import os
HOST = '192.168.1.7'
PORT = 9999
ADDRESS = (HOST, PORT)
PATH = "C:/Users/Nitesh Rathi/Desktop/RECV"
soc = socket(AF_INET, SOCK_STREAM)
soc.connect(ADDRESS)
print('connected to', ADDRESS)
while True:
filesize = soc.recv(255).decode('utf-8')
buff = int(filesize)
print("size of filename: ", filesize, 'bytes')
filename = soc.recv(buff).decode('utf-8')
if not filename: break
Path = os.path.join(PATH, filename)
print(Path)
file = open(Path, 'wb')
filedata = soc.recv(1024)
file.write(filedata)
file.close()
soc.close()
print('socket closed')
print('data recvd')