I'm not familiar with how data transmission works, but I gave my best shot trying to code a server and client-side JSON packet transmitter via Python. Essentially client.py generates random JSON packets and sends them to server.py which binds a port using a socket and listens for a JSON packet, which then stores the JSON packet as a file to prove the transmission was successful.
One problem I am aware of is that within my client.py, the sock class is kept being created and closed through each cycle. Though, if I write it like
while True:
json_packet = generate_json_packet()
send_json_packet(sock, json_packet)
time.sleep(1)
Python emits the following: ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine after the first successful received packet.
Server.py
# Server-Side that receives json packets from client over the network using port 5000. Then it saves the json packet to a file with the filename of current time.
import socket
import json
import random
import string
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 5000)
print('starting up on {} port {}'.format(*server_address))
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
# Function to receive json packets from client
def receive_json(conn):
data = conn.recv(1024)
data = data.decode('utf-8')
data = json.loads(data)
return data
# Saves json packets to file and name it with id
def save_json(data):
filename = ''.join(random.choice(
string.digits) for _ in range(3))
filename = filename + '.json'
with open(filename, 'w') as f:
json.dump(data, f)
if __name__ == '__main__':
while True:
# Wait for a connection
print('waiting for a connection')
connection, client_address = sock.accept()
try:
print('connection from', client_address)
# Receive the data in json format
data = receive_json(connection)
print('received {!r}'.format(data))
# Save the json packet to a file
filename = save_json(data)
print('saved to', filename)
finally:
# Clean up the connection
connection.close()
# Sends random json packets to server over port 5000
import socket
import json
import random
import time
def generate_json_packet():
# Generate random json packet with hashed data bits
return {
"id": random.randint(1, 100),
"timestamp": time.time(),
"data": hash(str(random.randint(1, 100)))
}
# Send json packet to server
def send_json_packet(sock, json_packet):
sock.send(json.dumps(json_packet).encode())
ip = "127.0.0.1"
port = "5000"
if __name__ == "__main__":
while True:
# Create socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to server
sock.connect((ip, int(port)))
# Generate random json packet
json_packet = generate_json_packet()
# Send json packet to server
send_json_packet(sock, json_packet)
time.sleep(1)
sock.close()
JSON, notjsonorJson. \$\endgroup\$