加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
client.py 3.95 KB
一键复制 编辑 原始数据 按行查看 历史
Yeedraw 提交于 2024-05-10 21:20 . 项目提交初始化
# Simple client library for the relay server, a communication server where two clients
# connect to and can message each other by name.
#
# It sends socket connections with the relay protocol and guarantees the delivery of
# the messages to the server and back to the client.
#
# 1. Registration: {"client_id": client_id}
# This informs the server the name of the current socket connection
#
# 2. Send message to: {"to": the_other_client_id, "data": any object}
# Informs the server to send the data to another known client
#
# USAGE:
# 1. connect(SERVER_IP, PORT, CLIENT_ID) connects to the server and registers as a CLIENT_ID
# 2. sendData(CLIENT_ID, DATA) sends any python object to the desired client
# 3. receiveData() locks the current thread until it receives an object back.
# 4. disconnect() closes the socket.
import socket # for connecting to the server
import time
import split_with_socket.utils.relay_protocol as protocol
import split_with_socket.utils.atomic_socket as atomic_socket
import pickle # object serialization
import base64 # Make sure the serialized object can be transformed into a string
import re
buffer_size = 35000
# instantiate
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_name = ''
last_message = ''
def connect(relay_server_host, relay_server_port, client_id):
global client_name
client_name = client_id
print('Starting Client ' + client_id) # show in terminal
# connect to the server
client_socket.connect((relay_server_host, relay_server_port))
# register this computer by name
atomic_socket.send(client_socket, protocol.register(client_id))
# Wait for 1 second otherwise socket concatenates the two sends
time.sleep(1)
def sendData(to, data):
global last_message
# print('Sending ' + data.__class__.__name__ + ' data to ' + to)
last_message = protocol.send(to, serializeObjToStr(data))
# print(data)
# print(serializeObjToStr(data))
atomic_socket.send(client_socket, last_message)
def receiveData():
while True:
try:
# print("进入receiveData函数")
result_list = []
msgRaw = atomic_socket.recv(client_socket)
msgRaw_list = re.findall(r'\{([^}]*)\}', msgRaw)
for i in range(len(msgRaw_list)):
# print(i)
obj = protocol.parse_data_msg('{' + msgRaw_list[i] + '}')
# print(type(obj))
if type(obj) is protocol.Repeat:
print('Repeating: ' + last_message)
atomic_socket.send(client_socket, last_message)
elif type(obj) is protocol.PartnerNotConnected:
print('Error: ' + obj.client_id + ' not connected')
elif type(obj) is protocol.ReceivedFrom:
# print("开始解码")
object = deserializeStrToObj(obj.data)
# print("解码结束")
# print('Received ' + object.__class__.__name__ + ' data from ' + obj.client_id)
result_list.append(object)
if i == len(msgRaw_list) - 1:
if len(result_list) == 1:
# print(type(result_list[0]))
return result_list[0]
else:
return result_list
except Exception as inst:
print(inst)
print("错误")
atomic_socket.send(client_socket, protocol.repeat(client_name))
return
def serializeObjToStr(data):
picked_byte_representation = pickle.dumps(data)
serialized_bytes = base64.b64encode(picked_byte_representation)
return serialized_bytes.decode('utf-8')
def deserializeStrToObj(str):
encodedStr = str.encode('utf-8')
picked_byte_representation = base64.b64decode(encodedStr)
return pickle.loads(picked_byte_representation)
def disconnect():
client_socket.close() # close the connection
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化