【问题标题】:Transfer files with sockets in Python 3在 Python 3 中使用套接字传输文件
【发布时间】:2016-07-26 02:05:48
【问题描述】:

我有以下客户端-服务器套接字应用程序将文件上传到服务器。

服务器代码:

    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 文件

【问题讨论】:

  • 如果你要进入一个无限循环,你不想在那里休息一下吗?

标签: python sockets python-sockets


【解决方案1】:

你可以改进你的循环。

  1. 使用while True 而不是while 1。当然它可以工作并且输入更少,但是如果你真的想要更少的输入,那么你应该使用 Perl。 while True 非常简单,几乎任何人都可以猜到它的含义 - while 1 只是 Python 没有 TrueFalse 时的保留。
  2. socket.recv 在没有更多内容可读取时返回一个空字符串。使用它。
  3. 您每次都通过循环打开文件。每次循环都会截断它。

以下是更好的方法:

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,并且您的循环将退出。

【讨论】:

  • 为什么 While True 比 while 1 更好?只是出于好奇
  • 我应该休息一下吗?
  • 这种方法行不通。我仍然得到一个空文件
  • 1 是没有 True 的早期 Python 版本的保留。 while True 更容易理解——即使是非程序员也应该能够理解。这里不需要休息 - 因为不是while True,而是while data。只要有数据要写入,这将继续写入数据。最终,发送者将停止发送任何数据,套接字将关闭,data 将是一个空字符串,其计算结果为False,您的循环将退出。
  • 我刚刚做了一个修改,应该可以帮助您进行调试。它会打印出你得到的任何数据。
猜你喜欢
  • 1970-01-01
  • 2011-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-04
  • 1970-01-01
相关资源
最近更新 更多