前言
tcp是一种常用的通信协议,使用者往往会有同时向客户端接收与发送数据的需求,在这里提供一种使用python多线程实现的方法。
代码
主函数
代码如下(示例):
主函数定义tcp线程,并打开线程
if __name__ == '__main__':
tcp = threading.Thread(target=ComRecSend) # 创建串口接收线程
tcp.start()
ComRecSend函数
代码如下(示例):
在ComRecSend函数中绑定端口,开启socket嵌套字,为了实现同时收发,又在tcp线程中为收发程序分别开启了线程
def ComRecSend():
global connect_flag
HOST =''
PORT = 2451
BUFSIZ = 1024
ADDR = (HOST,PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR) # 绑定IP地址和端口号
tcpSerSock.listen(5) # 监听,使得主动变为被动
while True:
print('正在等待连接....')
tcpCliSock, addr = tcpSerSock.accept() # 当来新的连接时,会产生一个的新的套接字为客户端服务
print(tcpCliSock)
print(addr)
print('连接成功')
connect_flag = 1
myrec = threading.Thread(target=rec,args=(tcpCliSock,BUFSIZ,))#接收线程
myrec.start()
mysend = threading.Thread(target=send,args=(tcpCliSock,))#发送线程
mysend.start()
tcpSerSock.close()
接收线程
代码如下(示例):
接收到的数据会被存在data中
def rec(tcpCliSock,BUFSIZ):
global connect_flag
while(connect_flag):
data = tcpCliSock.recv(BUFSIZ).decode("utf-8")
print(data)
if not data:
connect_flag = 0
print('connect error')
break
发送线程
代码如下(示例):
data会被发送
global connect_flag
delay = 1
data
while(connect_flag):
time.sleep(delay)
tcpCliSock.send((data)).encode("utf-8"))
tcpCliSock.close()
完整代码
import threading
from socket import *
import time
def rec(tcpCliSock,BUFSIZ):
global connect_flag
while(connect_flag):
data = tcpCliSock.recv(BUFSIZ).decode("utf-8")
print(data)
if not data:
connect_flag = 0
print('connect error')
break
def send(tcpCliSock):
global connect_flag
global decision_path
global path_change_flag
delay = 1
data ='1'
while(connect_flag):
time.sleep(delay)#间隔delay秒发一次
tcpCliSock.send((data).encode("utf-8"))
tcpCliSock.close()
def ComRecSend():
global decision_path,connect_flag
HOST =''
PORT = 2451
BUFSIZ = 1024
ADDR = (HOST,PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR) # 绑定IP地址和端口号
tcpSerSock.listen(5) # 监听,使得主动变为被动
while True:
print('正在等待连接....')
tcpCliSock, addr = tcpSerSock.accept() # 当来新的连接时,会产生一个的新的套接字为客户端服务
print(tcpCliSock)
print(addr)
print('连接成功')
connect_flag = 1
myrec = threading.Thread(target=rec,args=(tcpCliSock,BUFSIZ,))
myrec.start()
mysend = threading.Thread(target=send,args=(tcpCliSock,))
mysend.start()
tcpSerSock.close()
if __name__ == '__main__':
tcp = threading.Thread(target=ComRecSend) # 创建串口接收线程
tcp.start()