forked from p3t2ja9zs/dcs
parent
64a607e50b
commit
a1a73aa412
@ -0,0 +1,72 @@
|
||||
import socket
|
||||
import threading
|
||||
import struct
|
||||
from json import JSONEncoder, JSONDecoder
|
||||
from time import sleep
|
||||
|
||||
from loguru import logger
|
||||
from collections import deque
|
||||
|
||||
|
||||
def read_bytes(s: 'socket.socket', size: 'int') -> 'bytes':
|
||||
data = ''.encode('utf-8')
|
||||
while len(data) < size:
|
||||
rsp_data = s.recv(size - len(data))
|
||||
data += rsp_data
|
||||
if len(rsp_data) == 0:
|
||||
break
|
||||
return data
|
||||
|
||||
|
||||
def generate_request(request) -> 'bytes':
|
||||
request_bytes = JSONEncoder().encode(request).encode("utf-8")
|
||||
return struct.pack("!Q", len(request_bytes)) + request_bytes
|
||||
|
||||
|
||||
class Requester(threading.Thread):
|
||||
def __init__(self, request_map: 'dict', client_address: tuple):
|
||||
super().__init__()
|
||||
self.request_map = request_map
|
||||
self.daemon = True
|
||||
self.client_address = client_address
|
||||
self.responseJson = None
|
||||
pass
|
||||
|
||||
def request(self):
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) as socket_to_client:
|
||||
socket_to_client.connect(self.client_address)
|
||||
socket_to_client.sendall(generate_request(self.request_map))
|
||||
self.responseJson = JSONDecoder().decode(
|
||||
read_bytes(socket_to_client, struct.unpack('!Q', socket_to_client.recv(8))[0]).decode(
|
||||
"utf-8"))
|
||||
res.append(self.responseJson)
|
||||
return res
|
||||
|
||||
def get(self):
|
||||
try:
|
||||
return self.request()
|
||||
except:
|
||||
return None
|
||||
|
||||
def run(self) -> None:
|
||||
self.request()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
address = ('127.0.0.1', 7798)
|
||||
address1 = ('127.0.0.1', 7799)
|
||||
my_request = {'request': 'I am asking you...'}
|
||||
my_request1 = {'request1': 'I am asking you...'}
|
||||
res = deque()
|
||||
|
||||
requester = Requester(my_request, address)
|
||||
requester1 = Requester(my_request1, address1)
|
||||
requester1.start()
|
||||
requester.start()
|
||||
|
||||
requester1.join()
|
||||
requester.join()
|
||||
sleep(2)
|
||||
# print(requester1.get())
|
||||
# print(requester.get())
|
||||
print(res)
|
Loading…
Reference in new issue