iCodeLikeImDrunk
iCodeLikeImDrunk

Reputation: 17876

how do i get socket to accept more than one connection?

Currently I have a socket server that can only accept ONE connection. Any second connection, it just hangs and not do anything.

The server can get the message send from one client. I have the server to send back confirmation only for now.

server.py:

import socket, sys

# some vars
HOST = "localhost";
PORT = 4242;

# create the socket
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM);

# bind the socket to port
server_addr = (HOST, PORT);
print >>sys.stderr, "starting server %s on port %s" % (HOST, PORT);
soc.bind(server_addr);

# check for connections
soc.listen(1);

while True:
    # wait for a connection
    connection, client_address = soc.accept();
    try:
        # since just test
        # just send back whatever server receives
        while True:
            data = connection.recv(16);
            if data:
                connection.sendall(str(client_address[1]) + " said " + data);
    finally:
        connection.close();

client.py:

import socket, sys, thread

# some vars
HOST = "localhost";
PORT = 4242;

# create the socket
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM);

# connect to server/port
server_addr = (HOST, PORT);
print >>sys.stderr, "connecting to %s on port %s" % (HOST, PORT);
soc.connect(server_addr);

# try to send data over
while True:
    try:
        # send the message
        msg = raw_input("Message: ");
        soc.sendall(msg);

        # check if there is response
        amt_recd = 0;
        amt_expd = len(msg);

        while amt_recd < amt_expd:
            data = soc.recv(16);
            amt_recd += len(data);
            print >>sys.stderr, data, "\n";
    finally:
        msg = '';

Upvotes: 2

Views: 2182

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 178389

There is no exit condition from this infinite loop in the server:

while True:
    data = connection.recv(16)
    if data:
        connection.sendall(str(client_address[1]) + " said " + data)

If the client closes the connection data will be empty, but it will still continue looping. To fix:

while True:
    data = connection.recv(16)
    if not data:
        break
    connection.sendall(str(client_address[1]) + " said " + data)

Also, even after fixing this the server can only handle one connection at a time. If you desire to service multiple clients at once, you'll need to use select.select or spin off threads for each client connection.

As an aside, Python does not require semicolons at the end of statements.

Upvotes: 3

Related Questions