user8506085
user8506085

Reputation:

how to maintain connection between several clients and server in a Python Sockets program

below is a basic program that has the client enter a name, then it connects to the server and gets a response, and the server then appends the name to a list, the problem is when a second client connects to the server the first client loses connection and this happens for every client that connects. how do I solve this?

server.py :

import socket

s = socket.socket()
host = "127.0.0.1"
port = 5409
s.bind((host, port))

names = []

while True:
    s.listen(5)
    c, addr = s.accept() # Establish connection with client.
    print 'Got connection from', addr
    while True:
        try:
            name = c.recv(1024)
            print name
        except:
            print ""

        if name not in names:
            names.append(name)
            message = "Hello " + name
            c.sendall(message)

        print names
        break

client.py :

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = "127.0.0.1"          # Get local machine name
port = 5409                 # Reserve a port for your service.

name = raw_input("What Is your Name? ")

s.connect((host, port))
while True:
    try:
        s.send(name)
    except:
        break

    try:
        print s.recv(1024)
    except:
        break

Upvotes: 0

Views: 72

Answers (1)

UnoriginalNick
UnoriginalNick

Reputation: 327

You will need to make your server able to handle concurrent connections, either with multithreading, multiprocessing, or select.

The socketserver module provides convenient basic server classes using threading or multiprocessing. The official documentation has some good examples. Here is one using the threading module for concurrency:

import socket
import threading
import socketserver

class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):

    def handle(self):
        data = str(self.request.recv(1024), 'ascii')
        cur_thread = threading.current_thread()
        response = bytes("{}: {}".format(cur_thread.name, data), 'ascii')
        self.request.sendall(response)

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass

def client(ip, port, message):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.connect((ip, port))
        sock.sendall(bytes(message, 'ascii'))
        response = str(sock.recv(1024), 'ascii')
        print("Received: {}".format(response))

if __name__ == "__main__":
    # Port 0 means to select an arbitrary unused port
    HOST, PORT = "localhost", 0

    server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
    ip, port = server.server_address

    # Start a thread with the server -- that thread will then start one
    # more thread for each request
    server_thread = threading.Thread(target=server.serve_forever)
    # Exit the server thread when the main thread terminates
    server_thread.daemon = True
    server_thread.start()
    print("Server loop running in thread:", server_thread.name)

    client(ip, port, "Hello World 1")
    client(ip, port, "Hello World 2")
    client(ip, port, "Hello World 3")

    server.shutdown()
    server.server_close()

If you would like to build your own server without using socketserver, you can look at the source for the socketserver module (it's simple), or there are plenty of examples online of basic TCP/UDP servers using all three concurrency methods.

Upvotes: 1

Related Questions