从多线程聊天室接收数据时产生重叠的声音

时间:2019-02-25 04:04:08

标签: python python-3.x multithreading python-multithreading

我一直在尝试创建一个愚蠢的玩具,允许人们聊天,然后程序吸收文本并根据文本从服务器生成声音。我遇到了一个问题,尽管当不同的客户端在其聊天客户端中输入文本时,我能够让聊天室播放的声音彼此重叠,但是当单个客户端发送应创建重叠声音的数据时,顺序播放。我一直在尝试使用线程来实现我的目标,但到目前为止还没有成功。

from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
from Music_Handler import *
import pyo
import time

def accept_incoming_connections():
    """Sets up handling for incoming clients."""
    while True:
        client, client_address = SERVER.accept()
        print("%s:%s has connected." % client_address)
        client.send(bytes("Welcome to the chat! Now type your name and press enter!", "utf8"))
        addresses[client] = client_address
        Thread(target=handle_client, args=(client,)).start()

def handle_client(client):  # Takes client socket as argument.
    """Handles a single client connection."""

    name = client.recv(BUFSIZ).decode("utf8")
    enter_sound = client_enters_chat()
    enter_sound.out()
    welcome = 'Welcome %s! If you ever want to quit, type {quit} to exit.' % name
    client.send(bytes(welcome, "utf8"))
    msg = "%s has joined the chat!" % name
    broadcast(bytes(msg, "utf8"))
    clients[client] = name
    msg = client.recv(BUFSIZ)

    def client_loop(msg):
        while True:
            if msg == bytes("{quit}", "utf8"):
                client.send(bytes("{quit}", "utf8"))
                exit_sound = client_leaves_chat()
                exit_sound.out()
                client.close()
                del clients[client]
                broadcast(bytes("%s has left the chat." % name, "utf8"))
                time.sleep(1)
                break
            else:
                #Play Sound From Toy7structure
                TOY7_STRUCTURE.structure(msg)
                broadcast(msg, name+": ")
                print("Message: ", msg.decode("utf-8"))

    Thread(target=client_loop(msg)).start()

def broadcast(msg, prefix=""):  # prefix is for name identification.
    """Broadcasts a message to all the clients."""

    for sock in clients:
        sock.send(bytes(prefix, "utf8")+msg)

HOST = '127.0.0.1'
PORT = 33000
BUFSIZ = 1024
ADDR = (HOST, PORT)

SERVER = socket(AF_INET, SOCK_STREAM)
SERVER.bind(ADDR)

if __name__ == "__main__":
    SERVER.listen(5)
    print("Waiting for connection...")
    #Start formal structure here
    TOY7_STRUCTURE = structure_handler(BOUNDARY1, BOUNDARY2, BOUNDARY3, BOUNDARY4, BOUNDARY5)
    ACCEPT_THREAD = Thread(target=accept_incoming_connections)
    ACCEPT_THREAD.start()
    ACCEPT_THREAD.join()
    SERVER.close()

0 个答案:

没有答案