Python uses a single socket to send and receive information at the same time

The first is to import the required modules, including the content required by sockets and multithreading, and time is used to control the sending interval of information.

import time
import socket
import threading

1. Broadcast thread that sends information

Multiple ports are used here to simulate different addresses, and all the port addresses that need to be sent are stored in ports.
Note: The ports are not written in the parameters. In actual use, the parameters of the class are written or the ports are taken from the global variables according to the specific needs.

# 广播线程
class broadcast(threading.Thread):
	def __init__(self, threadID, name, interval, soc):
		threading.Thread.__init__(self)
		self.threadID = threadID
		self.name = name
		self.interval = interval
		self.soc = soc
	def run(self):
		while True:
			# 使用自定义的create_msg()方法创建要发送的文本信息
			msg = create_msg()
			msg = msg.encode(encoding='UTF-8')
			# 对所有port都进行一次发送
			for port in ports:
				self.soc.sendto(msg, ("127.0.0.1", port))
			# interval为每次发送给所有端口之后间隔的时间
			time.sleep(self.interval)

2. Processing thread that receives information

# 接收线程		
class recieve(threading.Thread):
	def __init__(self, threadID, name, soc):
		threading.Thread.__init__(self)
		self.threadID = threadID
		self.name = name
		self.soc = soc
	def run(self):
		while True:
			msg = ""
			addr = ""
			try:
				data, addr = self.soc.recvfrom(2048)
				msg = data.decode(encoding='UTF-8')
			except:
				pass
			# 利用自定义的deal_msg()方法处理接收的文本信息
			result = deal_msg(msg)
			# 可以根据获取的result在后面继续做一些其它操作

3. Create a thread

# 此处配置为UDP协议,根据具体需要调整
soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# run_port为当前socket运行的端口
soc.bind(("127.0.0.1", run_port))
# 创建发送线程,每轮发送间隔一秒
UPDATE_INTERVAL = 1
thread_broadcast = broadcast(1, "broadcast", UPDATE_INTERVAL, soc)
# 创建接收线程
thread_recieve = recieve(2, "recieve", soc)

4. Start the thread

# 启动线程
thread_broadcast.start()
thread_recieve.start()

You can also add some other threads according to specific needs, such as computing content.

Guess you like

Origin blog.csdn.net/starvapour/article/details/108416351