加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
buff.py 1.33 KB
一键复制 编辑 原始数据 按行查看 历史
JOHNSON 提交于 2021-07-27 12:17 . 仿 HTTP 协议传输
import json
from socket import socket
from typing import AnyStr
def _decode(data: AnyStr, decode: bool):
if decode:
data = data.decode("utf-8")
return data
def _encode(data: AnyStr, encode: bool):
if encode:
data = data.encode("utf-8")
return data
class Buff(object):
def __init__(self, sock: socket):
"""
:param sock:
"""
self.wbuff = sock.makefile("wb")
self.rbuff = sock.makefile("rb")
def read(self, size: int, decode: bool = False) -> AnyStr:
return _decode(self.rbuff.read(size), decode)
def readLine(self, deocde: bool = False) -> AnyStr:
return _decode(self.rbuff.readline(), deocde)
def write(self, data: AnyStr, encdoe: bool = True):
self.wbuff.write(_encode(data, encdoe))
def writeLine(self, data: AnyStr, encdoe: bool = True):
if isinstance(data, bytes):
data += b"\r\n"
else:
data += "\r\n"
self.write(data, encdoe)
def writeJson(self, data: dict, encode: bool = True, wrap: bool = False):
data = json.dumps(data)
data = _encode(data, encode)
if wrap:
self.writeLine(data, False)
self.write(data, False)
def send(self):
self.wbuff.flush()
def close(self):
self.wbuff.close()
self.rbuff.close()
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化