socketserver 모듈

1898 단어
  • SocketServer TCP 서버를 생성합니다
  • $ tsTservSS.py
      1 #!/usr/bin/python3
      2 
      3 from socketserver import (TCPServer as TCP, StreamRequestHandler as SRH)
      4 from time import ctime
      5 
      6 HOST = ''
      7 PORT = 6666
      8 ADDR = (HOST, PORT)
      9 
     10 #  
     11 class MyRequestHandler(SRH):
     12 
     13     #  handle 
     14     def handle(self):
     15         #  
     16         print('[+] ...connected from: %s: %d' % (self.client_address[0], self.client_address[1]))
     17         #  ,self.rfile.readline(), ,
     18         # self.wfile.write(), 
     19         self.wfile.write(b'[%s] %s' % (bytes(ctime(), 'utf-8'), self.rfile.readline()))
     20 
     21 
     22 tcpServ = TCP(ADDR, MyRequestHandler)
     23 print('[*] waiting for connection...')
     24 tcpServ.serve_forever()
    
    
  • SocketServer TCP 클라이언트를 만듭니다
  • $ tsTclntSS.py
      1 #!/usr/bin/python3
      2 
      3 from socket import *
      4 
      5 HOST = 'localhost'
      6 PORT = 6666
      7 BUFSIZ = 1024
      8 ADDR = (HOST, PORT)
      9 
     10 while True:
     11     tcpCliSock = socket(AF_INET, SOCK_STREAM)
     12     tcpCliSock.connect(ADDR)
     13     data = input(">>>")
     14     if data == 'exit':
     15        break
     16     #  \r
    17 tcpCliSock.send(b'%s\r
    ' % bytes(data, 'utf-8')) 18 data = tcpCliSock.recv(BUFSIZ) 19 if not data: 20 break 21 print(data.decode('utf-8').strip()) 22 23 tcpCliSock.close()
  • TCP 서버와 클라이언트를 실행합니다
  • #  1
    $ ./tsTservSS.py 
    [*] waiting for connection...
    [+] ...connected from: 127.0.0.1: 33166    # 
    [+] ...connected from: 127.0.0.1: 33168    # 
    [+] ...connected from: 127.0.0.1: 33170    # 
    
    #  2
    $ ./tsTclntSS.py 
    >>>hello
    [Mon Nov 27 14:02:51 2017] hello
    >>>good bey!
    [Mon Nov 27 14:02:53 2017] good bey!
    >>>exit
    

    좋은 웹페이지 즐겨찾기