TCP的时间戳服务器,TCP客户端连接并发送一个字符串以换行符结尾(\r\n).服务器会将字符串带上时间戳后回传给客户端。
from socketserver import (TCPServer as TCP,StreamRequestHandler as SRH)
from time import ctime
HOST = ''
PORT = 21567
ADDR = (HOST,PORT)
class MyRequestHandler(SRH):
def handle(self):
print('...connected from:',self.client_address)
self.wfile.write("[%s] %s".encode("utf-8") % (ctime().encode(),self.rfile.readline()))
tcpServ = TCP(ADDR,MyRequestHandler)
print('waiting for connection...')
tcpServ.serve_forever()
用网络调试助手发送一条字符串:Hello World!\r\n
回传结果:
[2020-04-08 15:44:04.753]# SEND ASCII>
Hello World!
[2020-04-08 15:44:04.753]# RECV ASCII>
[Wed Apr 8 15:44:03 2020] Hello World!