I’m trying to implement a small chat server-client pair in Python. I have already written both my server and my client, but I’m having a little problem trying to run the server on my website.
This example is from the docs. I modified it a little bit to support multiple clients:
#!/usr/bin/env python
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 9090
BUFFER_SIZE = 256
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
while True:
conn, addr = s.accept()
print('Connection address:', addr)
while True:
data = conn.recv(BUFFER_SIZE)
if not data: continue
# handle the request
conn.close()
This server uses a while loop, which means that it should only be run once. However, I can’t figure out how to run the server only once.
I understand that I had to do socket.accept() inside a while loop in order to work with more than one client, but the problem is actually running it on my web server and making it wait for connections forever.
Help me! ~Chance
For one thing, your server will handle multiple clients, but only one at a time. This is not so bad for request-response based servers (like a HTTP server). In your case, you probably want to keep an open connection to each client.
You might want to take a look at the SocketServer library. This library will help you create a server that will handle multiple clients at the same time. For this you can use an ThreadingMixin.
The example provided for this library is very much like a Chat Server, so you could use it as a basis for your own code.
In the server you need to create list of connected clients. You should create a RequestHandlder that will read incoming data from the clients in an infinite loop. Upon receiving data from the client, it should send the data to all other clients in the list.