python - (Python) 如何在不刷新的情况下实时接收消息?

标签 python server udp client

我遵循了一位名为 DrapsTV 的 YouTube 用户的教程。本教程是用 Python 2.7 编写的,并使用 UDP 进行网络聊天。我将其转换为 Python 3 并让一切正常工作。然而,线程的设置方式是我必须发送一条消息(或按 Enter 键,这是一条空白消息)来刷新和接收来自其他客户端的任何消息。这是视频,以防您可能需要: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()

最佳答案

@furas 善意地为我解释了我的问题:这不是我的接收方法有缺陷(例如我的线程或函数),而是输入调用阻止了客户端接收任何内容。因此,为了解决这个问题,我或其他遇到此问题的人需要找到一种方法来在按下某个按钮时调用输入,以便除非您打字,否则您可以接收消息或数据。

谢谢@furas! https://stackoverflow.com/users/1832058/furas

关于python - (Python) 如何在不刷新的情况下实时接收消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40569643/

相关文章:

sockets - 需要更多关于 listen system call linux 的见解

python 无我

server - 获取Dart中的所有子类

networking - TCP、UDP、SCTP、RUDP 还是 RAW?

TCP 在 UDP 上引起的数据包丢失和学士论文引用

xmpp - 使用 Smack 4.1.0 的 GCM XMPP 服务器

python - Jupyter打印语句问题

Python,一个带有索引组合的简单总和列表

python - 为什么在 python 3.3 上导入进程时会出现导入错误?

php - 无法访问cpanel,获取 “HTTP ERROR 500”