0
我試圖運行在不同的端口幾個插座,如下所示:運行多個插座與不同的端口在Python
插座:
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的第一個實例。我讀過「線程」庫,它可以在異步中運行多個進程,但無論如何沒有結果,因爲在控制檯中我看到「FIRST INITIALIZED」。如何運行第二個或第三個套接字偵聽器?可能有另一種方法來做到這一點。
我會推薦使用像['eventlet'](http://eventlet.net/),['gevent'](http://www.gevent.org/)這樣的基於事件的庫,或者if使用Python 3,本地['asyncio'](https://docs.python.org/3/library/asyncio.html)模塊。這將允許您同時監聽所有套接字並同時處理來自其中任何套接字的數據包,而無需使用線程開銷。 – augurar