[英]How can I recieve/send multiple messages at the same time in python? (Python Multithreading)
I have followed some instructions to make a chat app in python using socket, and it is working fine.我已经按照一些说明使用套接字在 python 中制作了一个聊天应用程序,并且工作正常。 However, due to the way it is written, you can only send messages when a message has been sent first.
但是,由于它的编写方式,您只能在首先发送消息时发送消息。 Basically, you can't send multiple messages at the same time.
基本上,您不能同时发送多条消息。 However, I would really like to incorporate this.
但是,我真的很想加入这个。 The person who made the tutorial said that this could be achieved through multi-threading, but didn't elaborate further.
制作教程的人说这可以通过多线程来实现,但没有进一步阐述。 Can someone explain what they mean?
有人可以解释他们的意思吗? Thanks.
谢谢。 Here is the sever side code:
这是服务器端代码:
import socket
import sys
import time
s = socket.socket()
host = socket.gethostname()
port = 8080
s.bind((host,port))
print("\n")
print(host)
print("\n")
name = input("Please enter your username: ")
s.listen(1)
print("\n")
print("Waiting for incoming connections")
print("\n")
conn, addr = s.accept()
print("Connected")
s_name = conn.recv(1024)
s_name = s_name.decode()
print("\n")
print(s_name, " has connected to the server")
print("\n")
conn.send(name.encode())
while 1:
message = input(">> ")
conn.send(message.encode())
message = conn.recv(1024)
message = message.decode()
print(message)
And the client side code:和客户端代码:
import socket
import sys
import time
s = socket.socket()
print("\n")
host = input(str("Please enter host name: "))
print("\n")
name = input("Please enter your username: ")
port = 8080
print("\n")
print("Connecting to ", host, "at port", port)
print("\n")
s.connect((host,port))
print("Connected")
s.send(name.encode())
s_name = s.recv(1024)
s_name = s_name.decode()
print("\n")
print(s_name, " has joined the chat")
while 1:
message = s.recv(1024)
message = message.decode()
print(message)
message = input(">> ")
s.send(message.encode())
Any help would be greatly appreciated.任何帮助将不胜感激。
if I understood well your problem the basic solution is that you have to create a while loop in which you accept connections and then handle them in a separate function-thread (serverside):如果我很好地理解了您的问题,则基本解决方案是您必须创建一个 while 循环,在该循环中您接受连接,然后在单独的函数线程(服务器端)中处理它们:
while True:
conn, addr = s.accept()
threading.Thread(target=connectionhandler, args=(conn,)).start()
def connectionhandler(conn):
#do things with the connection
let me know if this is a possible solution for you让我知道这是否适合您
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.