我有简单的 python 服务器和客户端。
服务器:
import SocketServer
import threading
class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print str(self.client_address[0]) + " wrote: "
print self.data
self.request.send(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 3288
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
客户:
import socket
import sys
from time import sleep
HOST, PORT = "localhost", 3288
data = "hello"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
sock.send(data + "\n")
received = sock.recv(1024)
sleep(10)
sock.send(data + "\n")
received = sock.recv(1024)
sleep(10)
sock.send(data + "\n")
received = sock.recv(1024)
finally:
sock.close()
这是我得到的输出:
服务器:
>python server.py
127.0.0.1 wrote:
hello
客户:
>python client.py
Traceback (most recent call last):
File "client.py", line 18, in <module>
received = sock.recv(1024)
socket.error: [Errno 10053] An established connection was aborted by the software in your host machine
我也在 linux 机器上试过。服务器只收到一条消息,然后我在第二条消息的 recv 语句中收到错误。我刚开始在 python 上学习网络,但我认为服务器出于某种原因正在关闭套接字。我该如何纠正这个问题?
最佳答案
为每个连接创建一个MyTcpHandler
对象,调用handle
处理客户端。 handle
返回时连接关闭,因此您必须在 handle
方法中处理来自客户端的完整通信:
class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
while 1:
self.data = self.request.recv(1024)
if not self.data:
break
self.data = self.data.strip()
print str(self.client_address[0]) + " wrote: "
print self.data
self.request.send(self.data.upper())
注意:当客户端关闭连接时,recv
返回 ''
,所以我在 recv 之后移动了
所以不会因为客户端只发送空白而误报。.strip()
关于python - 如何在客户端关闭套接字之前保持套接字打开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8627986/