Python3模拟TCP客户端发送和接收消息,端口自动重连

# coding:utf-8

import random
import socket
import time
import threading

host='127.0.0.1'
port=20001
count_send = 1;
count_recv=1;
count_conn=1;

def handle_client_send(clientsocket):
    global  count_send
    try:
        while True:
            send='fff91d9878085f02000000000000000000000000000000000000000000000000f1'
            clientsocket.send(bytes.fromhex(send))
            timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            print('模拟器-第 %d 次发送消息: %s' % (count_send, timestr))
            # print('休眠30s后继续发送')
            time.sleep(30)
            count_send=count_send+1
    except Exception as ex:
        print("模拟器-发送异常30秒后重连: %s" % ex)
        time.sleep(30)
        main()


def handle_client_recv(clientsocket):
    global count_recv
    while True:
        request = clientsocket.recv(1024)
        if not request:
            print("[#]连接断开...")
            break
        timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print('模拟器-第 %d 次收到消息: %s' % (count_recv, timestr))
        hexStr = request.hex()
        print("[>](HEX) Received: %s" % hexStr)
        count_recv=count_recv+1

def main():
    global count_conn
    try:
        clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print("第[%d]次  connect to %s:%d" % (count_conn,host, port))
        count_conn=count_conn+1
        clientsocket.connect((host, port))
        #循环发送
        client_handler_send = threading.Thread(target=handle_client_send, args=(clientsocket,))
        client_handler_send.start()
        #接收
        client_handler_recv_thread = threading.Thread(target=handle_client_recv, args=(clientsocket,))
        client_handler_recv_thread.start()
    except Exception as ex:
        print("模拟器-连接异常30秒后重连: %s" % ex)
        time.sleep(30)
        main()

if __name__ == '__main__':
    main()

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值