gpt4 book ai didi

python - 在 Python 中使用一个套接字接收和发送消息

转载 作者:行者123 更新时间:2023-12-01 09:31:14 27 4
gpt4 key购买 nike

我有一个 python 脚本,它已经使用套接字不时地向对等点发送消息。我想添加一个功能,该套接字异步监听入站消息,然后使用react,例如。处理内容并重新发送回复。是否可以仅使用一个套接字来完成此操作?我必须使用一个套接字,因为我的对等方在 localhost:30000 上创建其套接字。

编辑:

这是我迄今为止所做的尝试的一些代码。

监听线程的 Run() 方法:

def run(self):
print("Started listening to messages from peer...")
while True:
socketLock.acquire()
try:
self.listenToInboundMessages()
finally:
socketFlag.set()
socketLock.notify()
socketLock.release()

def listenToInboundMessages(self):
clientsocket.settimeout(1)
received = clientsocket.recv(BUFF)
print(received)

发送消息的线程的Run()方法:

def run(self):
print("Ready to send messages.")
while True:
print("Attempting to acquire lock...")
socketLock.acquire()
while not socketFlag.isAvailable():
socketLock.wait
print("Attempting to send message...")
clientsocket.send("Message for per")
socketLock.release()
time.sleep(1)

我使用 socketLock 条件变量和 socketFlag 类来协调两个线程。

最佳答案

对于 Windows,您可以使用 select 类将套接字连接列表过滤为 3 个列表:已准备就绪的套接字、已准备好写入的套接字以及有错误的套接字。

这是 p2p 套接字连接的基本实现(不是基于类的)。

import socket, select, time

s = socket.socket()
s.bind(("10.48.72.71", 8080))
s.listen(10)

connections = [s]

while True:
time.sleep(.1)

recv,write,err = select.select(connections,connections,connections)

for socket in recv:
if socket == s:
client,address = socket.accept()
connections.append(client)
else:
msg = socket.recv(4096).decode("UTF-8")
print("Recieved message from a socket, message was: "+str(msg))

for socket in write:
socket.send(bytes("Hi", "UTF-8"))

for socket in err:
print("Error with a socket")
socket.close()
connections.remove(socket)

关于python - 在 Python 中使用一个套接字接收和发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49955964/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com