在看python3核心编程第三版时,发现了好多问题,在网络编程这块现在都会报错
TypeError: %b requires a bytes-like object, or an object that implements bytes, not ‘str’
这次报错确实困扰了好久。
这里用到的就是
str --> bytes
str.encode()
bytes --> str
bytes.decode()
具体实现是以下代码,
# # SocketServer TCP 服务器
# -*- coding: UTF-8 -*-
from socketserver import TCPServer as TCP
from socketserver import StreamRequestHandler as SRH
from time import ctime
HOST = ''
PORT = 21567
ADDR = (HOST,PORT)
class MyRequestHandler(SRH):
def handle(self):
print('...connected frm: ', self.client_address)
self.wfile.write(b'[%s] %s' % ((ctime().encode()),self.rfile.readline()))
tcpServ = TCP(ADDR,MyRequestHandler)
print('waiting for connection...')
tcpServ.serve_forever()
# SocketServer TCP 客户端
# -*- coding: UTF-8 -*-
from socket import *