Created
September 13, 2022 14:25
-
-
Save ycaty/0f777816059d21e41abbce2ee213b175 to your computer and use it in GitHub Desktop.
Simple Client/Server Sockets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://gist.github.com/ycaty | |
import json | |
from uuid import uuid4 | |
import socket | |
import time | |
HOST = "127.0.0.1" | |
PORT = 65432 | |
def send_data(letter): | |
try: | |
# json.dumps(letter) => makes dict_letter into str_letter | |
# .encode() => makes str_letter into _bytes_letter | |
letter = json.dumps(letter).encode() | |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | |
s.connect((HOST, PORT)) | |
s.send(letter ) | |
ret_data = s.recv(1024) | |
ret_data = json.loads(ret_data) | |
letter = json.loads(letter) | |
if letter['id'] == ret_data['id']: | |
print ('woot id==id') | |
else: | |
while True: | |
print ('id!=id ... wut') | |
time.sleep(1) | |
except Exception as e: | |
print('error ', e) | |
return 0 | |
return 1 | |
while True: | |
id = str(uuid4()) | |
letter = {'data': {'one': 'uwo'}, | |
'id':id | |
} | |
ret = send_data(letter) | |
if ret: | |
print('success!') | |
else: | |
print('failed') | |
time.sleep(1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://gist.github.com/ycaty | |
import json | |
import socket | |
import time | |
HOST = "127.0.0.1" | |
PORT = 65432 | |
def do_stuff(dict): | |
try: | |
print (dict) | |
print (type(dict)) | |
dict = json.loads(dict) #_bytes to _dict | |
with open('data.json','w') as f: | |
json.dump(dict,f,indent=4) | |
f.flush() | |
f.close() | |
print ('wrote to file!!') | |
except Exception as e: | |
print ('error writing to file => ',e) | |
while True: | |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: | |
print ('hmm') | |
s.bind((HOST, PORT)) | |
s.listen() | |
conn, addr = s.accept() | |
with conn: | |
print("hi => ",addr) | |
data = conn.recv(1024) | |
print('got data => ', data) | |
do_stuff(data) | |
time.sleep(5) | |
#data = b'ratatatats' | |
conn.send(data) | |
time.sleep(5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment