1 Star 8 Fork 4

不懂d叛逆/pyccjh

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
ccjhConnect.py 2.60 KB
一键复制 编辑 原始数据 按行查看 历史
linap 提交于 2015-02-07 14:32 +08:00 . 添加异常显示
# -*- coding: utf-8 -*-
'''
Created on 2013-5-30
socket包装类,异步接收数据
@author: 不懂d叛逆
'''
import socket, threading, traceback
import ccjhEncoder, ccjhTimer
class ccjhConnect():
def __init__(self, NotifyFunc, Server, Port, ID, Password):
self.__decoder = ccjhEncoder.Decoder()
self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server = Server
self.__notify = NotifyFunc
self.port = Port
self.IP = "127.0.0.1"
self.__closed = True
self.__connecting = False
self.__thread = None
self.ID = ID
self.Password = Password
self.__bReconnect = True
return
def __del(self):
if self.__sock and self.__sock._closed == False:
self.__sock.close()
self.__sock = None
self.__closed = True
if self.__thread:
self.__thread.join();
self.__thread = None
return
# 关闭连接
def Close(self, bReconnect = True):
print("与服务器断开连接")
if self.__sock and self.__sock._closed == False:
self.__sock.close()
self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__closed = True
if self.__thread:
self.__thread._stop()
self.__thread = None
if bReconnect == False:
self.__bReconnect = False
# 10秒后重连
if self.__bReconnect and self.__connecting == False:
ccjhTimer.onceTimer(10, self.Connect)
return
# 连接服务器
def Connect(self):
if self.__connecting:return
print("连接服务器:%s:%d" % (self.server, self.port))
try:
self.__connecting = True
self.__sock.connect((self.server, self.port))
except:
print("连接失败")
self.__connecting = False
self.Close()
return
self.__connecting = False
self.__closed = False
self.__thread = threading.Thread(target = self.ReciveFunc, args = ())
self.__thread.start()
self.Login()
return
# 发送命令
def SendCmd(self, string):
if self.__sock and self.__sock._closed == False:
# print(string)
bins = ccjhEncoder.encode(string)
self.__sock.send(bins)
return
# 登录
def Login(self):
self.SendCmd("login %s WG2.06 %s %s \n" % (self.IP, self.ID, self.Password))
return
def Loc(self, LongID):
self.SendCmd("%d loc 0 12 12" % (LongID))
return
def ReciveFunc(self):
try:
while self.__closed == False:
buf = self.__sock.recv(2048)
if buf:
bufs = self.__decoder.decode(buf)
for b in bufs:
try:
self.__notify(b)
except Exception as e:
traceback.print_exc()
print("pkg:",b)
continue
else:
self.Close()
return
except Exception as e:
traceback.print_exc()
self.__sock.close()
self.__sock= None
self.__thread = None
return
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/panlizzx/pyccjh.git
git@gitee.com:panlizzx/pyccjh.git
panlizzx
pyccjh
pyccjh
master

搜索帮助