您当前的位置: 首页 >  Python

程序员正茂

暂无认证

  • 1浏览

    0关注

    283博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Python树莓派TCP客户端

程序员正茂 发布时间:2021-06-21 14:38:45 ,浏览量:1

import os,sys,time
import socket
import threading

#接收来自服务端的消息
def recv():
    global client
    global ip
    global connect
    while True:
        try:        
            byData = client.recv(30)
        except Exception as e:
            print("receiv error:",e)
            connect = False
            break
        data = byData.decode().strip()       
        print(data)        

#定义变量
ip = "192.168.0.101"
connect = False
i_beatMsg = 0

#客户端
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.settimeout(500)

while True:
    try:
        #自动重连
        if connect == False:
            print("try connect ", ip)
            client.connect((ip,9999))
            connect = True
            threading.Thread(target=recv).start()
            
        i_beatMsg+=1
        strlen = ""
        stringData=""
        if i_beatMsg > 50:
            #发送跳包消息
            i_beatMsg = 0
            stringData="hi"
            strlen = (str(len(stringData))).ljust(16)            
            client.send(bytes(strlen, 'UTF-8'));
            client.send(bytes(stringData, 'UTF-8'));
            
    except socket.error as  e:
        print("error1: %s" % e)
        connect = False
    time.sleep(0.01)

 

关注
打赏
1660743125
查看更多评论
立即登录/注册

微信扫码登录

0.0372s