我是靠谱客的博主 生动小蜜蜂,这篇文章主要介绍Python之Socket自动重连问题描述服务端代码客户端代码,现在分享给大家,希望可以做个参考。

问题描述

现有一个tcp客户端程序,需定期从服务器取数据,但由于种种原因(网络不稳定等)需要自动重连。

服务端代码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#! /usr/bin/env python #-*- coding:utf-8 -*- import socket import threading class ThreadedServer(object): def __init__(self, host, port): self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind((self.host, self.port)) def listen(self): self.sock.listen(5) while True: client, address = self.sock.accept() client.settimeout(60) threading.Thread(target = self.listenToClient,args = (client,address)).start() def listenToClient(self, client, address): size = 1024 while True: try: data = client.recv(size) if data: response = data client.send(response) print("secndLen: ",len(data)) else: raise error('Client disconnected') except: client.close() return False if __name__ == "__main__": while True: port_num = 12345 try: port_num = int(port_num) break except ValueError: print(ValueError) pass ThreadedServer('',port_num).listen()

客户端代码

注意需要用 python2 执行,python3 会报错

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#! /usr/bin/env python #-*- coding:utf-8 -*- import os,sys,time import socket def doConnect(host,port): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try : sock.connect((host,port)) except : pass return sock def main(): host,port = "127.0.0.1",12345 print(host,port) sockLocal = doConnect(host,port) while True : try : msg = str(time.time()) sockLocal.send(msg) print("send msg ok : ",msg) print("recv data :",sockLocal.recv(1024)) except socket.error : print("rnsocket error,do reconnect ") time.sleep(3) sockLocal = doConnect(host,port) except : print('rnother error occur ') time.sleep(3) time.sleep(1) if __name__ == "__main__" : main()

运行效果:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
(py27env) [root@local t1]# python tcpClient1_reconnect.py 127.0.0.1 12345 send msg ok : 1498891374.98 recv data : 1498891374.98 send msg ok : 1498891375.98 recv data : 1498891375.98 send msg ok : 1498891376.98 recv data : socket error,do reconnect send msg ok : 1498891381.99 recv data : 1498891381.99 send msg ok : 1498891382.99 recv data : 1498891382.99

最后

以上就是生动小蜜蜂最近收集整理的关于Python之Socket自动重连问题描述服务端代码客户端代码的全部内容,更多相关Python之Socket自动重连问题描述服务端代码客户端代码内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(88)

评论列表共有 0 条评论

立即
投稿
返回
顶部