我尝试在不同的端口上运行几个套接字,如下所示:
插座:
import socket
class Receiver:
TCP_IP = '127.0.0.1' # by default
TCP_PORT = 1999 # by default
BUFFER_SIZE = 1024
def __init__(self, TCP_IP, TCP_PORT):
self.TCP_IP = TCP_IP
self.TCP_PORT = TCP_PORT
def initialize(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((self.TCP_IP, self.TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print('Connection address:', addr)
while 1:
data = conn.recv(self.BUFFER_SIZE)
if not data: break
rdata = 'U'.encode() + data
print("received data:", data[1:5])
conn.send(rdata[0:5]) # echo
conn.close()
跑步者:
from NVGEmulator.Receiver import Receiver
import threading
class FireStarter:
def starter(self):
nvgEmu1 = Receiver('127.0.0.1', 2999)
print("FIRST INITIALIZED")
nvgEmu1.initialize()
nvgEmu2 = Receiver('127.0.0.1', 2998)
nvgEmu2.initialize()
print("SECOND INITIALIZED")
def starter_second(self):
nvgEmu2 = Receiver('127.0.0.1', 2998)
print("SECOND INITIALIZED")
nvgEmu2.initialize()
if __name__ == '__main__':
print("Receiver has been started")
fs = FireStarter()
thr = threading.Thread(target=fs.starter())
thr.start()
thr.join()
thr2 = threading.Thread(target=fs.starter_second())
thr2.start()
当我运行FireStarter时,它只运行socket的第一个实例。我已经读到有一个“线程”库可以异步运行多个进程,但无论如何都没有结果,因为在控制台我看到“第一次初始化”。如何运行第二个或第三个套接字侦听器?可能还有另一种方法可以做到这一点。你知道吗
你的代码有两个问题。你知道吗
第一个:第二个套接字正在等待第一个套接字结束,因为它被困在while循环中:
第二个是连接语句
thr.join()
,您强制第二个线程等待第一个线程,避免并行运行它。你知道吗我可能会遵循的方法是在Receiver类中的
initialize
函数中生成一个线程,并在那里管理线程(可能会扩展thread类),这样就避免了每次都自己生成一个新线程,而且代码也更加封装。你知道吗相关问题 更多 >
编程相关推荐