Files
2026-09-13 20:18:21 -05:00

69 lines
1.7 KiB
Python

# server.py
import socket
import shlex
import subprocess
from pathlib import Path
HOST = "0.0.0.0"
PORT = 5054
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen()
SCRIPT_DIR = Path(__file__).resolve().parent
print(f"Server listening on {HOST}:{PORT}")
def send_message(sock, message):
e_data = message.encode('utf-8')
#header for the message length
header = str(len(e_data)).zfill(10).encode('utf-8')
sock.sendall(header)
sock.sendall(e_data)
def receive_exact(sock, num_bytes):
received_data = b""
while len(received_data) < num_bytes:
chunk = sock.recv(num_bytes - len(received_data))
if not chunk:
raise ConnectionError("connection closed before the full message arrived")
received_data += chunk
return received_data
def receive_message(sock):
header = receive_exact(sock, 10)
if not header:
return None
message_length = int(header.decode('utf-8'))
received_data = receive_exact(sock, message_length)
return received_data.decode('utf-8')
while True:
conn, addr = server_socket.accept()
print(f"Connected by {addr}")
command = receive_message(conn)
if command is None:
conn.close()
continue
command_args = shlex.split(command)
if not command_args or command_args[0] != "grep":
response = "Invalid command. Please use the 'grep' command."
send_message(conn, response)
conn.close()
continue
command_args.insert(1, "-n")
result = subprocess.run(command_args, cwd=SCRIPT_DIR, capture_output=True, text=True)
send_message(conn, result.stdout + result.stderr)
conn.close()
server_socket.close()