Reputation: 965
I am having some trouble in getting this TCP server run properly... When I connect to it with netcat
, I can only send one message and then the server does not display the other send messages. When I place client, addr = tcp_socket.accept()
out of the while loop I can receive multiple messages but can only connect once...
What is the best way to tackles these problems?
Code
class TCP(threading.Thread):
def __init__(self, host, port):
self.port = port
threading.Thread.__init__(self)
def create_socket(self, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', port))
sock.listen(5)
return sock
def listen(self, tcp_socket):
while True:
client, addr = tcp_socket.accept()
print "Got connection from", addr
data = client.recv(1024)
if data:
print "TCP", data
def run(self):
self.listen(self.create_socket(self.port))
Upvotes: 0
Views: 889
Reputation: 5406
Here's a working example server application which has Socket.accept()
outside the loop:
class (threading.Thread):
def listenForClients(self, sock):
while True:
client, address = sock.accept()
client.settimeout(5)
threading.Thread( target = self.listenToClient, args = (client,address) ).start()
def listenToClient(self, client, address):
size = 1024
while True:
try:
data = client.recv(size)
if data:
response = "Got connection"
client.send(response)
else:
raise error('Client disconnected')
except:
client.close()
return False
def __init__(self, host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(5)
self.listenForClients(sock)
this uses a thread for each client because otherwise Socket.recv()
blocks so clients would have to take turns.
Upvotes: 1