2
目前我有一個只能接受一個連接的套接字服務器。任何第二個連接,它只是掛起,不做任何事情。如何讓套接字接受多個連接?
服務器可以從一個客戶端獲取消息發送。我現在只有服務器發回確認信息。
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 = '';
我會看看這個選擇模塊。我知道Python不需要「;」,我只是使用它,因爲它可以幫助我更容易地閱讀代碼。 – iCodeLikeImDrunk
好的,在看到一些例子後,我現在就來了。基本上服務器將有一個讀/寫套接字列表的列表,然後相應地服務它們。那是對的嗎? – iCodeLikeImDrunk
是的。同時查看Python附帶的'SocketServer'模塊。您可以輕鬆地編寫在線程中爲每個客戶端提供服務的代碼,並且該模塊的源代碼也非常易讀。 –