在python中使用多线程来创建一个基本的聊天室

时间:2017-08-19 17:15:11

标签: python sockets network-programming python-multithreading

我已经获得了夏季任务,使用套接字在python上创建聊天室,使用主套接字作为服务器连接到所有其他"客户端"套接字,每次客户端向服务器发送消息时,服务器都会将其发送给除发送它的客户端之外的其他人。问题是我需要制作它以便你可以同时写信息并接收它们,这是我不知道该怎么做的事情,所以我接受了我朋友的建议并尝试使用多个螺纹。

这就是我现在所拥有的,它应该变得更加复杂,但这是最基本的部分:

客户端

import socket
import thread
import time


def receive_messages(recieve_socket):
    while True:
        print recieve_socket.recv(1024)


def send_messages(send_socket):
    while True:
        data = raw_input()
        send_socket.send(data)    

def main():
    my_socket = socket.socket()
    my_socket.connect(('127.0.0.1', 8822))

    thread.start_new_thread(send_messages, (my_socket, ))
    thread.start_new_thread(receive_messages, (my_socket, ))
    time.sleep(1)  #this delay lets the threads kick in, otherwise the thread count is zero and it crashes
    while thread._count() > 1:
        pass

if __name__ == '__main__':
    main()

服务器

import socket
import select


waiting_messages = []
users = []


def add_new_user(user_socket):
    new_socket, address = user_socket.accept()
    users.append(new_socket)
    print "A new user has joined"


def remove_user(user_socket):
    users.remove(user_socket)
    print "A user has left"


def send_waiting_messages(wlist):
    for message in waiting_messages:
        receiving_socket, data = message
        if receiving_socket in wlist:
            receiving_socket.send(data)
            waiting_messages.remove(message)


def spread_messages(message, sending_user):
    receiving_list = users
    receiving_list.remove(sending_user)
    for user in receiving_list:
        waiting_messages.append((user, message))
    print "A user has sent a message"


def main():
    server_socket = socket.socket()
    server_socket.bind(('0.0.0.0', 8822))
    server_socket.listen(5)
    # users = []
    # messages_to_send = []

    while True:
        rlist, wlist, xlist = select.select([server_socket] + users, users, [])

        for current_socket in rlist:
            if current_socket is server_socket:
                add_new_user(server_socket)
            else:
                data = current_socket.recv(1024)
                if data == "quit":
                    remove_user(current_socket)
                else:
                    spread_messages(data, current_socket)

        send_waiting_messages(wlist)


if __name__ == '__main__':
    main()

问题是,当我尝试运行它时,第一条消息正常,但在第二条消息之后,服务器只发送了大量空白消息并停止发送我发送的消息。

我真的非常感谢这方面的帮助。

1 个答案:

答案 0 :(得分:0)

感谢帮助人员,最后我问了我的一个朋友,他告诉我在服务器上使用线程而不是选择并且效果很好!如果有兴趣的话,我稍后会发布代码。