如何让套接字接受多个连接?

时间:2012-11-26 03:22:42

标签: python sockets

目前我有一个只能接受一个连接的套接字服务器。任何第二个连接,只是挂起而不做任何事情。

服务器可以从一个客户端获取消息。我现在只有服务器发回确认。

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 = '';

1 个答案:

答案 0 :(得分:3)

服务器中的无限循环没有退出条件:

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

如果客户端关闭连接数据将为空,但它仍将继续循环。修复:

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

此外,即使在修复此问题之后,服务器也只能一次处理一个连接。如果您希望一次为多个客户端提供服务,则需要使用select.select或为每个客户端连接分离线程。

另外,Python在语句结尾处不需要分号。