tcp_client.py
# -*- coding:utf-8 -*-
# tcp 客户端,使用单例模式实现
# create: 2023-06-26
import socket
import time
import traceback
class TCPConnection:
__instance = None # 存储单例对象的类属性
def __new__(cls, host, port):
"""
实现单例模式,保证只有一个实例对象
"""
if cls.__instance is None:
cls.__instance = super().__new__(cls)
cls.__instance.host = host
cls.__instance.port = port
cls.__instance.socket = None
cls.__instance.connect()
return cls.__instance
def connect(self):
"""
连接tcp长连接
"""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.settimeout(10) # 设置超时时间为5秒
retry_time = 5
while retry_time > 0:
try:
self.socket.connect((self.host, self.port))
print('socket connect success')
break
except:
traceback.print_exc()
print('socket connect failed, retry after 5s')
time.sleep(5)
retry_time = retry_time - 1
def send_message(self, message, listen_long=False):
"""
发送消息并返回接收到的信息,如果断线则自动重连
"""
if isinstance(message, str):
message = message.encode("utf-8")
if not listen_long:
try_time = 3
while try_time > 0:
try:
print("send: ", message.hex())
self.socket.sendall(message)
print('send success')
response = self.socket.recv(2048)
print('recv: ', response.hex())
return response
except:
traceback.print_exc()
print('send failed, retry...')
try_time = try_time - 1
self.connect()
else:
try_time = 3
response = None
while try_time > 0:
try:
self.socket.sendall(message)
print("send: ", message.hex())
print('send success')
response = self.socket.recv(2048)
while True:
print('recv: ', response.hex())
tmp_recv = self.socket.recv(2048)
if tmp_recv is None:
break
else:
if tmp_recv[-1] == 0xff:
response = response + tmp_recv
break
response = response + tmp_recv
return response
except:
traceback.print_exc()
print('send failed, retry...')
try_time = try_time - 1
self.connect()
def close(self):
"""
关闭socket连接
"""
if self.socket:
self.socket.close()
self.socket = None
print('socket connection has been closed')
def set_host_port(self, host, port):
"""
修改host和port
"""
self.host = host
self.port = port
# self.close()
self.connect()
# 使用示例
if __name__ == '__main__':
tcp = TCPConnection(host='127.0.0.1', port=12123)
msg = '{"test":"hello"}'
recv = tcp.send_message(msg)
print(recv)
标签:socket,self,tcp,try,client,time,print,recv,python3
From: https://www.cnblogs.com/brian-sun/p/18516827