我正在尝试使用sockets(python)创建一个简单的聊天应用程序。客户机可以向服务器发送消息,服务器只需将消息广播给除已发送消息的客户机之外的所有其他客户机。
客户端有两个线程,它们将永远运行
send
: Send simply sends the cleints message to server.
receive
: Receive the message from the server.
服务器还有两个线程,它们将永远运行
accept_cleint
: To accept the incoming connection from the client.
broadcast_usr
: Accepts the message from the client and just broadcast it to all other clients.
但我得到了错误的输出(请参考下图)。所有线程都假设一直处于活动状态,但有时客户端可以发送消息,有时则不能。比如说,特蕾西发了4次“嗨”,但它没有广播,当约翰说了2次“再见”,然后1次它的信息被广播。我不确定服务器好像有什么问题。请告诉我怎么了。
下面是代码。
聊天室客户端.py
import socket, threading
def send():
while True:
msg = raw_input('\nMe > ')
cli_sock.send(msg)
def receive():
while True:
sen_name = cli_sock.recv(1024)
data = cli_sock.recv(1024)
print('\n' + str(sen_name) + ' > ' + str(data))
if __name__ == "__main__":
# socket
cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect
HOST = 'localhost'
PORT = 5023
cli_sock.connect((HOST, PORT))
print('Connected to remote host...')
uname = raw_input('Enter your name to enter the chat > ')
cli_sock.send(uname)
thread_send = threading.Thread(target = send)
thread_send.start()
thread_receive = threading.Thread(target = receive)
thread_receive.start()
聊天室服务器.py
import socket, threading
def accept_client():
while True:
#accept
cli_sock, cli_add = ser_sock.accept()
uname = cli_sock.recv(1024)
CONNECTION_LIST.append((uname, cli_sock))
print('%s is now connected' %uname)
def broadcast_usr():
while True:
for i in range(len(CONNECTION_LIST)):
try:
data = CONNECTION_LIST[i][1].recv(1024)
if data:
b_usr(CONNECTION_LIST[i][1], CONNECTION_LIST[i][0], data)
except Exception as x:
print(x.message)
break
def b_usr(cs_sock, sen_name, msg):
for i in range(len(CONNECTION_LIST)):
if (CONNECTION_LIST[i][1] != cs_sock):
CONNECTION_LIST[i][1].send(sen_name)
CONNECTION_LIST[i][1].send(msg)
if __name__ == "__main__":
CONNECTION_LIST = []
# socket
ser_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind
HOST = 'localhost'
PORT = 5023
ser_sock.bind((HOST, PORT))
# listen
ser_sock.listen(1)
print('Chat server started on port : ' + str(PORT))
thread_ac = threading.Thread(target = accept_client)
thread_ac.start()
thread_bs = threading.Thread(target = broadcast_usr)
thread_bs.start()
我试着避开你说的虫子。客户端将被询问一次用户名,此“uname”将包含在要发送的数据中。查看我对“发送函数所做的操作。
为了便于可视化,我在所有收到的邮件中添加了一个“\t”。
您还必须相应地修改服务器代码。
服务器.py
服务器端的变化是:连接的用户和发言的用户不再出现。我不知道如果你的目的是联系客户,这是否意味着那么多。如果您想通过服务器严格监控客户机,可能还有其他方法。
好的,我之前在评论中撒了谎,对不起。问题实际上在服务器上的
broadcast_usr()
函数中。它在recv()
方法中阻塞,并阻止除当前选定用户之外的所有用户在通过for
循环时在同一时间讲话。为了解决这个问题,我更改了server.py程序,为它接受的每个客户端连接生成一个新的广播usr线程。我希望这能有帮助。相关问题 更多 >
编程相关推荐