0

Im trying to have multiple clients be able to connect to a server however when a second user connects it kicks the other client off the server as you cant have 2 clients connected to a socket and i was wondering if there was anything around this.

server.py

import socket

def Main():
    host = '10.41.13.228'
    port = 5000


    s = socket.socket()
    s.bind((host,port))

    s.listen(1)


    name = input("Please Enter your name - ")
    while True:
        c, addr = s.accept()
        print("Connection from: " + str(addr))
        data = c.recv(1024).decode('utf-8')
        print(data)
    c.close()

if __name__ == '__main__':
    Main()

Client.py

import socket

def Main():
    host = '10.41.13.228'
    port = 5000

    s = socket.socket()
    s.connect((host, port))


   name = input("Please enter your name - ")
   message = input("-> ")
   while True:
        while message != 'q':
            ToSend = (str(name) + " - " + str(message))
            s.sendall(ToSend.encode('utf-8'))
            message = input("-> ")
        s.close()

if __name__ == '__main__':
     Main()
bradley plater
  • 1,272
  • 2
  • 9
  • 16

2 Answers2

0

The problem i noticed in your code is s.listen method. Where you are listening to only one client connection. You could increase the amount to have more clients connected to the server.

sathya Narrayanan
  • 499
  • 1
  • 5
  • 16
0

As described in the example from the docs:

Note that a server must perform the sequence socket(), bind(), listen(), accept() (possibly repeating the accept() to service more than one client), while a client only needs the sequence socket(), connect(). Also note that the server does not sendall()/recv() on the socket it is listening on but on the new socket returned by accept().

Therefore, there are two missing parts in your code.

  1. As already commented, your listen() method should take a 2 as argument (as you intend to have 2 clients).
  2. You should call accept() twice. Remember to keep in mind the comment of the example. Quoting again:

    note that the server does not sendall()/recv() on the socket it is listening on but on the new socket returned by accept()

Out of topic. It is indeed a good practice to have a keyword such as 'exit' to break from the loop of your server once recieved.

rpastor
  • 1
  • 1