mbah_bejo

Tugas1_progjar.py

Mar 29th, 2022 (edited)
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.23 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # Foundations of Python Network Programming, Third Edition
  3. # https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter03/tcp_sixteen.py
  4. # Simple TCP client and server that send and receive 16 octets
  5.  
  6. import argparse, socket
  7. import sys
  8. import glob
  9. import time
  10.  
  11. def recvall(sock, length):
  12.     data = b''
  13.     while len(data) < length:
  14.         more = sock.recv(length - len(data))
  15.         if not more:
  16.             raise EOFError('was expecting %d bytes but only received'
  17.                            ' %d bytes before the socket closed'
  18.                            % (length, len(data)))
  19.         data += more
  20.     return data
  21.  
  22. def server(interface, port):
  23.     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  24.     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  25.     sock.bind((interface, port))
  26.     sock.listen(1)
  27.     print('Listening at', sock.getsockname())
  28.  
  29.     print('Waiting to accept a new connection')
  30.     sc, sockname = sock.accept()
  31.     print('We have accepted a connection from', sockname)
  32.     print('  Socket name:', sc.getsockname())
  33.     print('  Socket peer:', sc.getpeername())
  34.     #message = recvall(sc, 16)
  35.     while True:
  36.         len_msg = recvall(sc, 3)
  37.         message = recvall(sc, int(len_msg)).decode()
  38.         pesan = message.split()
  39.         if(pesan[0]=="ping"):
  40.             msgPing = pesan[1:]
  41.             msgPHasil = " ".join(msgPing)
  42.             print("Terima : ", msgPHasil)
  43.  
  44.         elif(pesan[0]=="ls"):
  45.             List=""
  46.             if(len(pesan)==1):
  47.                 listFile=glob.glob("./*")
  48.             else:
  49.                 msgL = " ".join(pesan[1:])
  50.                 print(msgL)
  51.                 listFile = glob.glob(msgL)
  52.             for i in listFile:
  53.                 List += i +"\n"
  54.             print(List)
  55.             List = List.encode()
  56.             len_List = b"%03d" % (len(List),)
  57.             listFix = len_List + List
  58.             sc.sendall(listFix)
  59.  
  60.         elif(pesan[0]=="get"):
  61.             pesan2 = " ".join(pesan[1:-1])
  62.             pesanGet = pesan2 + '/' + pesan[-1]
  63.  
  64.             f = open(pesanGet, "rb")
  65.             b = f.read()
  66.             #print(len(b))
  67.             f.close()
  68.  
  69.             print("fetch:", pesan2, "size: ", len(b), "lokal:", pesan[-1])
  70.  
  71.         elif(pesan[0]=="quit"):
  72.             sc.sendall(b"client shutdown...")
  73.             sc.close()
  74.             print("server shutdown..")
  75.             sys.exit(0)
  76.  
  77. def client(host, port):
  78.     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  79.     sock.connect((host, port))
  80.     print('Client has been assigned socket name', sock.getsockname())
  81.     # msg = " "
  82.     while True:
  83.         msg = input(">  ")
  84.         pesan = msg.encode()
  85.         len_msgE = b"%03d" % (len(pesan),)
  86.         pesan = len_msgE + pesan
  87.         sock.sendall(pesan)
  88.         msg=msg.split()
  89.         if(msg[0]=="ping"):
  90.             pesan = msg[1:]
  91.             pesanPing = " ".join(pesan)
  92.             print("Terima :", pesanPing)
  93.         elif(msg[0] =="ls"):
  94.             reply = recvall(sock, 3)
  95.             listFile = recvall(sock, int(reply)).decode()
  96.             print(listFile)
  97.         elif(msg[0]=="get"):
  98.             pesan = " ".join(msg[1:-1])
  99.             pesanGet = pesan+"/"+msg[-1]
  100.             f = open(pesanGet, "rb")
  101.             b = f.read()
  102.             # print(len(b))
  103.             f.close()
  104.             print("fetch",pesan,"size :" ,len(b), "lokal",msg[-1])
  105.         elif (msg[0] == "quit"):
  106.             reply = recvall(sock, 16)
  107.             print('The server said', repr(reply))
  108.             time.sleep(1)
  109.             sock.close()
  110.             break
  111.         else:
  112.             print("unknown command...")
  113.  
  114. if __name__ == '__main__':
  115.     choices = {'client': client, 'server': server}
  116.     parser = argparse.ArgumentParser(description='Send and receive over TCP')
  117.     parser.add_argument('role', choices=choices, help='which role to play')
  118.     parser.add_argument('host', help='interface the server listens at;'
  119.                         ' host the client sends to')
  120.     parser.add_argument('-p', metavar='PORT', type=int, default=1060,
  121.                         help='TCP port (default 1060)')
  122.     args = parser.parse_args()
  123.     function = choices[args.role]
  124.     function(args.host, args.p)
  125.  
Add Comment
Please, Sign In to add comment