目前我有一个只能接受一个连接的套接字服务器。任何第二个连接,它只是挂起而不做任何事情。
服务器可以获取从一个客户端发送的消息。我现在只有服务器发回确认。
服务器.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 = '';