【BIGTREETECH CB1核心板&PI4B试用】第七篇 Python TCP通信
[复制链接]
准备搞一搞TCP网络通信
TCP的python学习参考python核心编程和python网络编程两本书
有了这两个基础,基本python的TCP简单应用也不在话下了
编写了一个bigtreetcp.py(SERVER) 一个computer.py
一新建py文件
新建一个bigtreetcp.py文件
二PC电脑创建一个coputertcp.py文件
使用pycharm
三运行py文件
PC机上运行
输入数据测试
通信成功
电脑端的代码
import socket
import time
import sys
SERVER_IP = "192.168.43.17" # 树莓派的IP地址
SERVER_PORT = 8888
print("Starting socket: TCP...")
server_addr = (SERVER_IP, SERVER_PORT)
socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
try:
print("Connecting to server @ %s:%d..." % (SERVER_IP, SERVER_PORT))
socket_tcp.connect(server_addr)
break
except Exception:
print("Can't connect to server,try it latter!")
time.sleep(1)
continue
print("Please input:")
while True:
try:
data = socket_tcp.recv(512)
if len(data) > 0:
print("Received: %s" % data)
command = input()
socket_tcp.send(command.encode())
time.sleep(1)
continue
except Exception:
socket_tcp.close()
socket_tcp = None
sys.exit(1)
MCU端的代码
#coding:utf-8
#import necessary package
import socket
import time
import sys
HOST_IP = "192.168.43.17" #树莓派的IP地址
HOST_PORT = 8888
print("Starting socket: TCP...")
#1.create socket object:socket=socket.socket(family,type)
socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("TCP server listen @ %s:%d!" %(HOST_IP, HOST_PORT) )
host_addr = (HOST_IP, HOST_PORT)
#2.bind socket to addr:socket.bind(address)
socket_tcp.bind(host_addr)
#3.listen connection request:socket.listen(backlog)
socket_tcp.listen(1)
#4.waite for client:connection,address=socket.accept()
socket_con, (client_ip, client_port) = socket_tcp.accept()
print("Connection accepted from %s." %client_ip)
str='hello python tcp server'
str=str.encode()
socket_con.send(str)
print("Receiving package...")
###主循环
while True:
try:
data=socket_con.recv(512)
if len(data)>0:
print("Received:%s"%data)
socket_con.send(data)
time.sleep(1)
continue
except Exception:
socket_tcp.close()
sys.exit(1)
|