Python客户端服务器传输.txt不写入文件 [英] Python Client Server Transfer .txt Not Writing to File
问题描述
我正在尝试使用TCP套接字在Python中编写一个简单的客户端/服务器,但是我似乎无法弄清楚为什么文件没有传输.
I'm trying to write a simple client/server in Python using a TCP socket but I can't seem to figure out why the file is not transferring.
客户:
import socket
HOST = '' #server name goes in here
PORT = 3820
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((HOST,PORT))
fileToSend = open('myUpload.txt', 'rb')
while True:
data = fileToSend.readline()
if data:
socket.send(data)
else:
break
fileToSend.close()
print 'end'
socket.close()
exit()
打印结束只是为了告诉我这个客户已经完成.
The print end is just to tell me that this client finished.
服务器:
import socket
HOST = ''
PORT = 3820
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((HOST, PORT))
socket.listen(1)
file = open('myTransfer.txt', 'wb')
while True:
conn, addr = socket.accept()
data = conn.recv(1024)
print data
if data:
file.write(data)
else:
file.close()
break
socket.close()
exit()
服务器能够打印出客户端发送的正确数据,但是无法将其保存到myTransfer.txt中.即使我有一个break语句,该程序似乎也无法终止.任何帮助都将非常有帮助.谢谢!
The server was able to print out the correct data that was sent by the client but it was not able to save it into myTransfer.txt. The program seems to not be able to terminate even though I have a break statement in there. Any help would be very helpful. Thanks!
推荐答案
您正在while循环内调用accept
.因此,只有一个recv
调用可以接收数据,因此永远不会调用break
.
You are calling accept
inside the while-loop. So you have only one recv
-call that receives data, so break
is never called.
顺便说一句.您应该使用sendall
来保证所有数据都已发送.
Btw. you should use sendall
, that guarantees, that all data is sent.
客户:
import socket
HOST = '' #server name goes in here
PORT = 3820
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((HOST,PORT))
with open('myUpload.txt', 'rb') as file_to_send:
for data in file_to_send:
socket.sendall(data)
print 'end'
socket.close()
服务器:
import socket
HOST = ''
PORT = 3820
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((HOST, PORT))
socket.listen(1)
conn, addr = socket.accept()
with open('myTransfer.txt', 'wb') as file_to_write:
while True:
data = conn.recv(1024)
print data
if not data:
break
file_to_write.write(data)
socket.close()
这篇关于Python客户端服务器传输.txt不写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!