Home > Mobile >  Socket only accepts one Connection
Socket only accepts one Connection

Time:11-24

My Python socket chat with multithreading only accepts one connection. If I try to connect a second client it doesn't work. On the client side it seems like everything is okay but if i try to send a second message from client 2 the message doesn't arrive.

import socket
import threading

class TxtSocket:
    
    def __init__(self, host="127.0.0.1" , port=5555):
        self.host = host
        self.port = port
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.bind((self.host, self.port))
        print("Socket was created")
        

    def server(self):
        self.s.listen()
        print("Server is listening")
        conn, addr = self.s.accept()
        print(f"{addr} is now connected.")
        while True:
            data = conn.recv(1024).decode("utf8")
            print(data)
            if not data:
                break
    

if __name__ == "__main__":
    txtsocket = TxtSocket()
    for i in range(0, 26):
        t = threading.Thread(target=txtsocket.server())
        t.start()

# Client
import socket

def Text():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("127.0.0.1", 5555))
    print("Connected")
    while True:
        message = input("Deine Nachricht: ")
        message = message.encode("utf8")
        s.send(message)
Text()

CodePudding user response:

Need couple mods to the server to handle multiple clients.

  • Need main loop to keep accepting new connections and forking off the processing to a thread
  • Create a new thread to handle client connection when socket gets a new connection.

The following server code works with multiple running clients as specified above.

# server
import socket
import threading

class TxtSocket:
    
    def __init__(self, host="127.0.0.1", port=5555):
        self.host = host
        self.port = port
        self.thread = 0
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.bind((self.host, self.port))
        print("Socket was created")
        
    def handle(self, conn, addr):
        self.thread  = 1
        print(f"Thread-{self.thread} {addr} is now connected")
        while True:
            data = conn.recv(1024).decode("utf8")
            print(data)
            if not data:
                break
        conn.close()

    def server(self):
        # specify the number of unaccepted connections that the server
        # will allow before refusing new connections.
        self.s.listen(5)
        print("Server is listening")
        while True:
            conn, addr = self.s.accept()
            # create new thread to handle the client connection
            t = threading.Thread(target=self.handle, args=(conn, addr))
            t.start()

if __name__ == "__main__":
    txtsocket = TxtSocket()
    txtsocket.server()
  • Related