我有簡單的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的網絡,但我認爲服務器出於某種原因正在關閉套接字。我該如何糾正?
這可能有所幫助:http://stackoverflow.com/a/20421867/2290820 – user2290820 2013-12-06 16:07:20