I want to implement a parallel server. The server should acceppt more than one client at the same time. So that the client can send messages to the server.
A serial server is working awesome. I can connect, write, close and can connect again, no problem. Now I want to implement threads. So like: For every new client, there have to be a new thread that handles a TCP socket with one client.
My code for the serial server:
#!/usr/bin/python # This is server.py file
import socket # Import socket module
import time
while True:
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Please wait...')
time.sleep(2)
c.send('Thank you for connecting with your admin. Please write now.')
while True:
msg = c.recv(1024)
if not msg:
s.close()
break
elif msg == "close1234567890":
print ("Connection with %s was closed by the client." % (addr[0]))
else:
print "%s: %s" % (addr[0], msg)
My TRY for the parallel server:
import socket
import time
import thread
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
s.bind((host, 50999))
s.listen(5)
def session(conn, addr):
while True:
print 'Got connection from', addr
conn.send('Please wait...')
time.sleep(2)
conn.send('Thank you for connecting with your admin. Please write now.')
while True:
msg = conn.recv(1024)
if not msg:
s.close()
break
elif msg == "close1234567890":
print ("Connection with %s was closed by the client." % (addr[0]))
else:
print "%s: %s" % (addr[0], msg)
while True:
conn, addr = s.accept()
try:
thread.start_new_thread(session(conn, addr))
finally:
s.close()
Error: I start the server, no prob. Then I start the Client and everything is normal. I can write and the messages are printed out by the server. Then I start a second client, but in this windows nothing happens. No chance to write from the second client.
Sry, I am absolutely beginner with threads ;)