Python--socketserver
tsTservSS.py:#!/usr/bin/env pythonfrom socketserver import (TCPServer as TCP, StreamRequestHandler as SRH)from time import ctimeHOST = ''PORT = 21567ADDR = (HOST, PORT)# 继承SRH父类class MyRequ...
·
tsTservSS.py:
#!/usr/bin/env python
from socketserver import (TCPServer as TCP, StreamRequestHandler as SRH)
from time import ctime
HOST = ''
PORT = 21567
ADDR = (HOST, PORT)
# 继承SRH父类
class MyRequestHandler(SRH):
# 重写handle()方法
def handle(self):
# StreamRequestHandler类把输入和输出的套接字看做类似文件的对象
# readline()获取客户端信息,write()将信息发送给客户端
print('---Connected from: ' ,
self.client_address, self.wfile.write(('[%s]%s'%(ctime(), self.rfile.readline().decode('utf-8'))).encode('utf-8')))
# 使用给定的地址和请求处理类创建TCP服务器
tcpServ = TCP(ADDR, MyRequestHandler)
print('Waiting for connection...')
# 无限的等待并服务于客户端
tcpServ.serve_forever()
tsTclntSS.py:
#!/usr/bin/env python
from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
while True:
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
data = input('>')
if not data:
break
tcpCliSock.send(('%s\r\n' % data).encode('utf-8'))
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print(data.strip().decode('utf-8'))
tcpCliSock.close()
更多推荐
所有评论(0)