0
我已经按照DrapsTV的名字从YouTuber上看了一个教程。本教程由Python 2.7制作,并使用UDP进行网络聊天。我将它转换为Python 3并让所有东西都起作用。但是,设置线程的方式是我必须发送消息(或按回车,这是一条空白消息)以刷新并接收来自其他客户端的消息。下面是视频柜面你可能会需要它:https://www.youtube.com/watch?v=PkfwX6RjRaI(Python)如何在不刷新的情况下实时接收消息?
这里是我的服务器代码:
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()
问题是nto套接字或线程,但'input()'阻止所有程序。但是,对于无阻塞的'input()'没有标准的方法。你可以创建两个线程 - 一个只用于从服务器接收,一个用于发送到服务器和'input()'。 – furas
@furas会解决吗? –