# 导入socket库
import socket
import threading
import time
import datetime
class SocketClient:
def __init__(self, ip, port):
self.IP = ip
self.PORT = port
""" socket 建立链接 """
def connect(self):
while True:
server2 = (self.IP, self.PORT)
global socket_client2
socket_client2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
socket_client2.connect(server2)
except Exception as message:
print('连接服务器报错%s' % message)
time.sleep(1)
continue
else:
print('连接服务器成功')
threading.Thread(target=self._recv).start()
break
""" socket发送数据 """
def _send(self, msg):
try:
socket_client2.send(msg.encode("gbk"))
print('发送给服务器的消息:%s' % msg)
except Exception as message:
print('连接服务器报错%s' % message)
self.connect()
""" socket接收数据 """
def _recv(self):
try:
while (True):
res = socket_client2.recv(1024)
if not res:
break
print(datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S') + ' 收到服务器的消息:%s' % res)
except Exception as message:
print('收到服务器的消息报错%s' % message)
self.connect();
if __name__ == '__main__':
client = SocketClient("192.168.2.122", 2024);
client.connect()
Python Socket 客户端实现,支持掉线重连
最新推荐文章于 2024-07-06 02:08:52 发布