客户端:
import socket
import json
#服务端为tcp方式,客户端也采用tcp方式 默认参数即为tcp
client = socket.socket()
#访问的服务器的ip和端口
ip_port=('127.0.0.1',8888)
#连接主机
client.connect(ip_port)
#定义发送消息循环
while True:
# 接受主机信息 每次接收缓冲区1024个字节
data = client.recv(1024)
# 打印接受的数据
print(data.decode())
msg_input = input("请输入exit退出:")
# client.send(msg_input.encode())
client.send(json.dumps({'OperatorType':2,'PlatFormCode':'10008'}).encode())
if msg_input == 'exit':
break
服务端:
import socket
import threading
import sys
import json
ip_port=('127.0.0.1',8888)
msg = '链接服务端成功'
def server_start():
sk = socket.socket()
try:
#绑定监听
sk.bind(ip_port)
#最大连接数
sk.listen(5)
except Exception as e:
print(e)
sys.exit(1)
print('启动成功,等待链接',ip_port)
while True:
conn,addr = sk.accept()
conn.send(msg.encode())
t = threading.Thread(target=dispose_data,args=(conn,addr))
t.start()
def dispose_data(conn,addr):
while True:
try:
data = conn.recv(1024)
# 具体处理数据
# print('客户端{0}的消息'.format(addr),data.decode())
transfer_recept_resolve(data,conn)
except ConnectionResetError as e:
print('客户端{0}断开'.format(addr),e)
conn.close()
sys.exit(1)
if data == exit:
print('{0} client connect close'.format(addr))
break
conn.close()
# 处理数据
def transfer_recept_resolve(data,conn):
try:
server_obj = json.loads(data.decode(), object_hook = json2class)
server_obj.toString()
conn.send(json.dumps({'status':200,'message':'success'}).encode())
except Exception as e:
conn.send(json.dumps({'status':400,'message':'数据格式错误,请检查字段'}).encode())
print('字段类型错误')
# 初始化数据类
class ServerObject:
OperatorType = 1
PlatFormCode = '001'
def __init__(self, OperatorType,PlatFormCode):
super(ServerObject, self).__init__()
self.OperatorType = OperatorType
self.PlatFormCode = PlatFormCode
def toString(self):
print('OperatorType:{0},PlatFormCode:{1}'.format(self.OperatorType,self.PlatFormCode))
## json2class
def json2class(data):
return ServerObject(data['OperatorType'],data['PlatFormCode'])
if __name__ == "__main__":
server_start()
评论区