简体   繁体   English

如何在 Python3 的套接字聊天室中发送和接收,而不会在打字时中断客户端?

[英]How can I send and recieve in a socket chat room in Python3 without the client being interrupted while typing?

I am currently attempting to create a command line client-server model chat room, however, I have ran into a problem, the problem being that if someone else talks in the chat room, it writes over the input that the other clients are trying to type, which is horrible for a multitude of reasons, especially if said server gets larger.我目前正在尝试创建一个命令行客户端 - 服务器模型聊天室,但是,我遇到了一个问题,问题是如果其他人在聊天室中说话,它会覆盖其他客户端尝试的输入类型,由于多种原因,这很可怕,尤其是当所述服务器变大时。 I tried multi-threading, thinking that that would fix my problems, but it did not.我尝试了多线程,认为这可以解决我的问题,但事实并非如此。 Here is the client-side code that I am using currently:这是我目前使用的客户端代码:

import socket
import threading
while_loop = True
def recv():
    while while_loop == True:
        server_message = client.recv(2048)
        print(server_message.decode('utf-8'))
rt = threading.Thread(target=recv, args=())
def send():
    while while_loop == True:
        message_to_send = input(">>> ")
        client.sendall(bytes(message_to_send, 'utf-8'))
st = threading.Thread(target=send, args=())
rt.start()
st.start()
st.join()
rt.join()

Is there a way that I can make it (without holding up input) to both send and recieve messages in real-time?有没有办法让我(无需阻止输入)实时发送和接收消息? Thank you for your time, it is appreciated.感谢您的时间,不胜感激。

I know input() freezes the output until it gets an input so use pynput or keyboard.我知道 input() 会冻结输出,直到获得输入为止,因此请使用 pynput 或键盘。 Example:例子:

import keyboard
import time

while True:
   time.sleep(1)
   print("Listening for input...")
   print(keyboard.read_key())

You might need to use another thread to collect input then send:您可能需要使用另一个线程来收集输入然后发送: 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM