LyonL
LyonL

Reputation: 83

Python, make an exclusive TCP connection

I made a lot of research on Google and this website to have a answer to this simple topic. I want an exclusive connection between a TCP server in python and other clients. The first client connects to the server, and if others clients try to connect on the server, they must be rejected.

I only can manage the server code, the protocol and client are not editable.

# 1) Socket creation
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 2) binding
try:
    mySocket.bind((HOST, PORT))
except socket.error:
    print "socket connection failed"
    sys.exit()


while 1:
    # 3) Waiting for a client
    print "Ready, waiting for connection"
    try :
        mySocket.listen(0)
    except socket.error:
        print "connection lost"
        sys.exit()

    # 4) Accept connection
    connexion, adresse = mySocket.accept()
    print "Client connecté, adresse IP %s, port %s" % (adresse[0], adresse[1])

    while 1:
        # infinite loop while the client is connected. Therorically for ever
        try :
           msgClient = connexion.recv(1024)
        except socket.error:
           # connection lost
           break;

        # protection against empty packet
        if len(msgClient) == 0 :
           break;
        #[Here is my code to process incoming packets]
        bla bla bla 
    print "Connection lost"

When I read the socket manual, call the function listen(0) should close connection for other client. In the life, the second client has no rejected connection. If further information is required, I can provide them.

Upvotes: 1

Views: 496

Answers (1)

Armali
Armali

Reputation: 19375

if you want to reject connections, you have to close the server socket after the first client connects. – Daniel

Upvotes: 1

Related Questions