我已经使用了一个名为DrapsTV的YouTuber教程。本教程是在Python 2.7中完成的,并使用UDP进行网络聊天。我将其转换为Python 3并使一切工作正常。但是,设置线程的方式是我必须发送消息(或按回车键,这是一条空白消息)来刷新并接收来自其他客户端的任何消息。以下是您可能需要的视频:https://www.youtube.com/watch?v=PkfwX6RjRaI
这是我的服务器代码:
from socket import *
import time
address = input("IP Address: ")
port = input("Port: ")
clients = []
serversock = socket(AF_INET, SOCK_DGRAM)
serversock.bind((address, int(port)))
serversock.setblocking(0)
quitting = False
print("Server is up and running so far.")
while not quitting:
try:
data, addr = serversock.recvfrom(1024)
if "Quit" in str(data):
quitting = True
if addr not in clients:
clients.append(addr)
print(time.ctime(time.time()) + str(addr) + ": :" + str(data.decode()))
for client in clients:
serversock.sendto(data, client)
except:
pass
serversock.close()
这是我的客户代码:
from socket import *
import threading
import time
tLock = threading.Lock()
shutdown = False
def receiving(name, sock):
while not shutdown:
try:
tLock.acquire()
while True:
data, addr = sock.recvfrom(1024)
print(str(data.decode()))
except:
pass
finally:
tLock.release()
address = input("IP Address: ")
port = 0
server = address, 6090
clientsock = socket(AF_INET, SOCK_DGRAM)
clientsock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
clientsock.bind((address, int(port)))
clientsock.setblocking(0)
rT = threading.Thread(target=receiving, args=("RecvThread", clientsock))
rT.start()
nick = input("How about we get you a nickname: ")
message = input(nick + "> ").encode()
while message != "q":
if message != "":
clientsock.sendto(nick.encode() + "> ".encode() + message, server)
tLock.acquire()
message = input(nick + "> ").encode()
tLock.release()
time.sleep(0.2)
shutdown = True
rT.join()
clientsock.close()
答案 0 :(得分:1)
@furas已经为我解释了我的问题:我的接收方法不是有缺陷的(例如我的线程或函数),是输入调用阻止客户端不接收任何东西。因此,为了解决这个问题,我或其他任何有此问题的人需要找到一种方法来在按下某个按钮时调用输入,这样除非您输入,否则您可以接收消息或数据。