2

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

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

服务器.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();

客户端.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 = '';
4

1 回答 1

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 不需要在语句末尾使用分号。

于 2012-11-26T03:29:35.767 回答