加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
miniclient.py 2.00 KB
一键复制 编辑 原始数据 按行查看 历史
Xvar 提交于 2021-11-27 18:18 . save init
import pickle
import struct
import socket
import threading
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(("127.0.0.1", 9003))
class CClientSocket(object):
def __init__(self, oSocket):
self.m_Socket = oSocket
self.m_MsgBuf = b""
self.m_SocketLen = 0
def RecvMsg(self):
while True:
if self.m_SocketLen == 0:
try:
self.m_MsgBuf += self.m_Socket.recv(4)
except:
break
if len(self.m_MsgBuf) >= 4:
sLen = self.m_MsgBuf[:4]
self.m_MsgBuf = self.m_MsgBuf[4:]
iLen = struct.unpack("i", sLen)[0]
self.m_SocketLen = iLen
else:
break
else:
try:
self.m_MsgBuf += self.m_Socket.recv(self.m_SocketLen)
except:
break
if len(self.m_MsgBuf) >= self.m_SocketLen:
sMsg = self.m_MsgBuf[:self.m_SocketLen]
self.m_MsgBuf = self.m_MsgBuf[self.m_SocketLen:]
self.m_SocketLen = 0
oPackage = pickle.loads(sMsg)
self.OnCommand(oPackage)
else:
break
def OnCommand(self, oPackage):
if oPackage:
for sMsg in oPackage:
MsgInfo = pickle.loads(sMsg)
print(MsgInfo)
oClientSocket = CClientSocket(clientsocket)
class CReceiveThread(threading.Thread):
def __init__(self, thread_name):
super(CReceiveThread, self).__init__(name=thread_name)
def run(self):
while True:
oClientSocket.RecvMsg()
oNetWorkThread = CReceiveThread("receive")
oNetWorkThread.start()
while True:
sMsg = input("what do you want to send?")
sPackage = pickle.dumps({"msg":sMsg})
iLen = len(sPackage)
sBuff = struct.pack("i", iLen) + sPackage
clientsocket.send(sBuff)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化