我有一个python脚本,它已经不时地使用套接字发送消息。我想添加一个功能,该套接字异步侦听入站消息,然后作出反应,例如。处理内容并重新发送回复。是否可以只使用一个插座?我必须使用一个套接字,因为我的对等体在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
类来协调两个线程。
答案 0 :(得分:1)
对于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)