socketserver模块

2017-11-27  本文已影响0人  疯帮主
  1. 创建 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()

  1. 创建 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\n终止符
 17     tcpCliSock.send(b'%s\r\n' % 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()
  1. 执行 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
上一篇 下一篇

猜你喜欢

热点阅读