【发布时间】:2016-07-03 18:56:12
【问题描述】:
我正在尝试使用套接字 (python) 创建一个简单的聊天应用程序。客户端可以向服务器发送消息,服务器只需将消息广播给所有其他客户端,发送消息的客户端除外。
客户端有两个线程,永远运行
send: Send 只是将客户端消息发送到服务器。
receive:从服务器接收消息。
服务器也有两个线程,永远运行
accept_cleint:接受来自客户端的传入连接。
broadcast_usr:接受来自客户端的消息并将其广播给所有其他客户端。
但是我得到了错误的输出(请参考下图)。所有线程都假设一直处于活动状态,但有时客户端可以发送消息,有时却不能。例如,Tracey 发送了 4 次“嗨”但未广播,当约翰说“再见”2 次然后 1 次其消息被广播。服务器上似乎有一些thread synchronization 问题,我不确定。请告诉我有什么问题。
下面是代码。
chat_client.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()
chat_server.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()
【问题讨论】:
-
我认为问题出在您的客户端线程循环中,尽管您的服务器也需要能够处理客户端断开连接。
-
仅供参考,Twisted 是一个用于制作线程服务器的 Python 库。
标签: python multithreading sockets synchronization chat