re connect client to server after closing
I'm using a code witch permits only 4 connection on 4 different ports. This code is working but when a client is closing the connection, it can't re-establish connection. Connection is refused. Think it is because the thread is closed. How to solve this ? I can't change the ports number...
enter code here
-- coding: cp1252 --
from socket import *
BUFF = 25
def server(host, port):
def response(key):
return 'Server response: ' + key
def handler(clientsock,addr):
while 1:
data = clientsock.recv(BUFF)
if not data: break
print repr(addr) + ' recv:' + repr(data)
clientsock.send(response(data))
print repr(addr) + ' sent:' + repr(response(data))
if "close" == data.rstrip(): break # type 'close' on client console to close connection from the server side
clientsock.close()
print addr, "- closed connection" #log on console
addr = (host, port)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serversock.bind(addr)
serversock.listen(1)
clientsock, addr = serversock.accept()
handler(clientsock, addr)
if name ==' main ': import threading
HOST = '192.168.0.12'
PORTS = [10001,10002,10003,10004]
threads = []
for port in PORTS:
th = threading.Thread(target=server, args=(HOST, port))
th.start()
threads.append(th)
I'm not familiar with Python, but I will give it a shot.
In your thread, you probably need add a loop to accept new connections. serversock.accept() and the call "handler" would be in that loop. That should allow a client to again connect to the server when a client closes a connection.
Here is how I suspect it should look (no including error checking and with no knowledge of Python):
while 1:
clientsock, addr = serversock.accept()
handler(clientsock,addr);
链接地址: http://www.djcxy.com/p/56438.html
上一篇: 无法读取来自客户端程序的输入
下一篇: 关闭后重新连接客户端到服务器