简体   繁体   English

Python Socket - 同时发送/接收消息

[英]Python Socket - Send/Receive messages at the same time

Basically I have been working on a simple chat room using socket and thread.基本上我一直在使用套接字和线程开发一个简单的聊天室。 In my client I can receive and send messages, my issue is that one comes before another in a loop, so if I am sending a message I will only receive data once I have sent a message.在我的客户端中,我可以接收和发送消息,我的问题是在循环中一个在另一个之前,所以如果我发送消息,我只会在发送消息后接收数据。 I want it to work like any other chat room, where I could receive a message when I am sending a message, any help will help greatly.我希望它像任何其他聊天室一样工作,在我发送消息时可以收到消息,任何帮助都会有很大帮助。 This is my basic client:这是我的基本客户:

import socket
import sys

###########
HOST = '25.0.18.52'
PORT = 9999
###########

name = input("Enter your name: ")
s = socket.socket()
s.connect((HOST,PORT))

while 1:
    message = input("Message: ")
    s.send("{}: {}".format(name, message).encode('utf-8'))
    data = s.recv(1024)
    a = data.decode("utf-8") 
    print(a)

You should keep 2 threads: one for listening and the other for receiving.您应该保留 2 个线程:一个用于侦听,另一个用于接收。 In your while loop, you should remove the listener part, and keep the code in a different thread.在您的while循环中,您应该删除侦听器部分,并将代码保留在不同的线程中。 This way you can receive and type on the console at the same time.这样您就可以同时在控制台上接收和输入。

def recv():
    while True:
         data = s.recv(1024).decode()
         if not data: sys.exit(0)
         print data

Thread(target=recv).start()

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

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