在Python 2.7中创建一个消息传递应用程序,我遇到了一个问题。该应用程序的想法是创建一个命令行应用程序,其前提是一个用户可以运行服务器,而其他多个用户可以使用客户端程序连接到它。问题是:一旦一个客户端连接,服务器接受并显示来自第一个客户端的消息以进行连接,并且不显示来自任何其他客户端的消息。
服务器
import socket
import sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = raw_input("Enter IP address: ")
port = input("Enter Port: ")
server_address = (ip, port)
print >>sys.stderr, ' Starting up on %s port %s' % server_address
sock.bind(server_address)
while True:
sock.listen(1)
while True:
print>>sys.stderr, 'Waiting for connection'
connection, client_address = sock.accept()
connection, client_address2 = sock.accept()
try:
print >>sys.stderr, 'Connection from ', client_address
print >>sys.stderr, 'Connection from ', client_address2
while True:
data = connection.recv(500)
print >>sys.stderr, 'Recieved "%s" ' % data
finally:
connection.close()
客户
import socket
import sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = raw_input("Enter IP Address: ")
port = input("Enter Port: ")
name = raw_input("What is your name? ")
server_address = (ip, port)
print >>sys.stderr, 'Connecting to %s port %s' % server_address
sock.connect(server_address)
while True:
try:
message = raw_input()
print >>sys.stderr, 'Sending "%s"' % message
sock.sendall(message + " : " + name)
amount_recieved = 0
amount_expected = len(message)
finally:
print("Sent")
connection.close()
在服务器代码中,服务器将打印连接到它的客户端,但只显示来自其中一个的客户端。