Skip to content

Instantly share code, notes, and snippets.

@sudopower
Created April 26, 2023 06:10
Show Gist options
  • Save sudopower/20e9b63768fcd11394a637ac7848fc11 to your computer and use it in GitHub Desktop.
Save sudopower/20e9b63768fcd11394a637ac7848fc11 to your computer and use it in GitHub Desktop.
tcp ip socket recorder
import socket
import time
import select
HOST = '0.0.0.0'
PORT = 8000
PING_RATE = 5
CHANNEL = 'timing'
BUFFER_SIZE_10_MB = 10 * 1024 * 1024 # 10 MB buffer
LOGIN_MSG = 'LOGIN:::{"user":"my_user","password":"my_pass","app":"Manual Test", "app_ver":"1.0.0","protocol":" AKS V2 Protocol", "protocol_ver":"1.0.0"}'
def send(sock, msg):
msg = msg + '\r\n'
sock.send(msg.encode())
def receive(sock, buffer_size=1024):
data = ''
while True:
try:
chunk = sock.recv(buffer_size)
if not chunk:
break
data += chunk.decode()
if data.endswith('\r\n'):
break
except Exception as e:
print(f"Exception: {e}")
continue
return data.strip()
def main():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
try:
sock.connect((HOST, PORT))
except Exception as e:
print(f"Error connecting to server: {e}")
send(sock, LOGIN_MSG)
response = receive(sock, buffer_size=1024)
# Get the ping rate from the response
# ping_rate = int(response.split(":")[3])
ping_rate = PING_RATE
# Join the channel
send(sock, f"JOIN::{CHANNEL}")
response = receive(sock,buffer_size=1024)
# print("JOINED MSG: ",response)
last_ping_time = time.time()
inputs = [sock]
outputs = []
# Listen to the channel and write messages to a file
with open(f"{CHANNEL}.txt", "w") as f:
while inputs:
try:
# Send a ping message to the server at the specified rate
if time.time() - last_ping_time > ping_rate:
send(sock, "PING::")
outputs.append(sock)
last_ping_time = time.time()
# Check if any sockets are ready to read/write
readable, writable, _ = select.select(inputs, outputs, [], 1)
for s in readable:
if s is sock:
# Receive data from the server
data = receive(sock, buffer_size=BUFFER_SIZE_10_MB)
if data:
if data.startswith('JSON'):
# This is a channel message
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
message = f"{timestamp}|{data}"
print(message)
f.write(message + '\n')
elif data.startswith('ACK'):
# This is an ACK message
outputs.remove(sock)
else:
# Handle the output sockets
s.sendall(b'PING::')
outputs.remove(s)
inputs.append(s)
# Check for errors
for s in readable + writable:
if s.fileno() < 0:
print("ERROR: Socket error")
inputs.remove(s)
except Exception as e:
print(f"Exception: {e}")
continue
if __name__ == '__main__':
main()
import socket
import threading
import time
def handle_client(client_sock, client_addr):
print(f"New client connected: {client_addr}")
try:
# Wait for login response
data = client_sock.recv(1024).decode().strip()
if not data.startswith('LOGIN:::'):
print("Invalid login response")
return
# Send login message
login_message = 'LOGIN:++::{"name":"timing","password":"password123"}\r\n'
client_sock.sendall(login_message.encode())
# Wait for client to join channel
data = client_sock.recv(1024).decode().strip()
if not data.startswith('JOIN::timing'):
print("Invalid login response")
return
# Send join acknowledgment message
login_message = 'JOIN:++:timing:\r\n'
client_sock.sendall(login_message.encode())
# Loop to receive messages
while True:
try:
data = client_sock.recv(10240).decode().strip()
if not data:
continue
# Handle ping message
if data == 'PING::':
ping_message = 'ACK:+::\r\n'
client_sock.send(ping_message.encode())
time.sleep(2)
# Send channel JSON message
login_message = 'JSON:3::{“timing”'
client_sock.sendall(login_message.encode())
login_message = ':{}}\r\n'
client_sock.sendall(login_message.encode())
except Exception as e:
print(f"Error receiving message: {e}")
except Exception as e:
print(f"Error handling client: {e}")
finally:
client_sock.close()
print(f"Client disconnected: {client_addr}")
def start_server():
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('0.0.0.0', 8000)
server_sock.bind(server_address)
server_sock.listen(5)
print(f"Server listening on {server_address}")
while True:
client_sock, client_addr = server_sock.accept()
client_thread = threading.Thread(target=handle_client, args=(client_sock, client_addr))
client_thread.start()
start_server()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment