使用 Python(套接字)创建一个简单的聊天应用程序

2023-12-01

我正在尝试使用套接字(python)创建一个简单的聊天应用程序。客户端可以向服务器发送消息,服务器只需将消息广播给除发送消息的客户端之外的所有其他客户端。

客户端有两个线程,永远运行

send:发送只是将客户端的消息发送到服务器。

receive:接收来自服务器的消息。

服务器也有两个线程,它们永远运行

accept_cleint:接受来自客户端的传入连接。

broadcast_usr:接受来自客户端的消息并将其广播给所有其他客户端。

但我得到了错误的输出(请参阅下图)。所有线程都假设始终处于活动状态,但有时客户端可以发送消息,有时却不能。举例来说,Tracey 发送“hi”4 次但未广播,当 John 说“bye”2 次后,其消息被广播 1 次。好像有一些thread synchronization服务器有问题,我不确定。请告诉我出了什么问题。

enter image description here

下面是代码。

聊天客户端.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()

好吧,我之前在评论中撒了谎,抱歉。问题实际上出在broadcast_usr()服务器上的功能。它阻塞在recv()方法并阻止除当前选定的用户之外的所有用户在整个过程中同时讲话for环形。为了解决这个问题,我更改了 server.py 程序,为它接受的每个客户端连接生成一个新的 Broadcast_usr 线程。我希望这有帮助。

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)
        thread_client = threading.Thread(target = broadcast_usr, args=[uname, cli_sock])
        thread_client.start()

def broadcast_usr(uname, cli_sock):
    while True:
        try:
            data = cli_sock.recv(1024)
            if data:
                print "{0} spoke".format(uname)
                b_usr(cli_sock, uname, data)
        except Exception as x:
            print(x.message)
            break

def b_usr(cs_sock, sen_name, msg):
    for client in CONNECTION_LIST:
        if client[1] != cs_sock:
            client[1].send(sen_name)
            client[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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Python(套接字)创建一个简单的聊天应用程序 的相关文章