我有以下客户端 - 服务器套接字应用程序将文件上传到服务器。
import socket,sys,SocketServer
class EchoRequestHandler(SocketServer.BaseRequestHandler):
def setup(self):
print self.client_address, 'connected!'
self.request.send('hi ' + str(self.client_address) + '\n')
def handle(self):
while 1:
myfile = open('test.txt', 'w')
data = self.request.recv(1024)
myfile.write(data)
print 'writing file ....'
myfile.close()
def finish(self):
print self.client_address, 'disconnected!'
self.request.send('bye ' + str(self.client_address) + '\n')
if __name__=='__main__':
server = SocketServer.ThreadingTCPServer(('localhost', 50000), EchoRequestHandler)
server.serve_forever()
import socket
import sys
HOST, PORT = "localhost", 50000
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((HOST, PORT))
# Receive data from the server and shut down
received = sock.recv(1024)
date = open('file_t.txt').read()
sock.sendall(data + "\n")
finally:
sock.close()
print "Sent: {}".format(data)
print "Received: {}".format(received)
然而,在服务器端,控制台输出是不停的"写入文件...."最后文件没有存储,它是一个空的test.txt文件
答案 0 :(得分:1)
你可以改善你的循环。
while True
而不是while 1
。当然它的工作原理并且输入较少,但如果你真的想减少打字,那么你应该使用Perl。 while True
非常简单,几乎任何人都可以猜到其含义 - while 1
只是Python没有True
或False
socket.recv
返回一个空字符串,此时无需阅读。使用它。这是一个更好的方法:
def handle(self):
# With block handles closing - even on exceptions!
with open('test.txt', 'w') as outfile:
data = 'fnord' # just something to be there for the first comparison
while data:
data = self.request.recv(1024)
print('writing {!r} to file ....'.format(data))
outfile.write(data)
这种方法不需要中断 - 因为它不是while True
while data
。只要字符串非空,字符串将评估为True
,因此只要有要写入的数据,这将继续写入数据。最终,发送方将停止发送任何数据,套接字将关闭,数据将为空字符串,其结果为False,您的循环将退出。