EchoServer设计到实现(五)

本文介绍了一个基于GoLang的项目如何通过增加操作包来支持字符串的回文判断、反转和随机化等功能,并讨论了现有代码的问题及改进方向。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里增加一点难度,顺便可以检测一下这个项目的扩展性。

新的需求:支持字符串的回文,反转,随机化
简单设计:添加一个操作包,主要完成上述需求,每个函数实现一个功能。主函数链接操作包和服务包,完成上述功能。
代码实现:
package protocol
import (
    "bytes"
    "encoding/binary"
)

const (
    //ConstLength 字符串长度
    MsgLength = 4
)

type Protocol struct {
    msgBuf []byte
    //ReaderChannel chan []byte
}

func New() *Protocol {
    pro := &Protocol{msgBuf: make([]byte, 0)} //readerChannel:make(chan []byte,1024)}
    //go pro.Depack()
    return pro
}

//PushStream 添加缓冲区节流
func (pro *Protocol) PushStream(buf []byte) {
    pro.msgBuf = append(pro.msgBuf, buf...)
}

//Enpack  压缩
func (pro *Protocol) Enpack(message []byte) []byte {
    Header := make([]byte, 0)
    return append(append(Header, IntToBytes(len(message))...), message...)
}

//Depack 解压
func (pro *Protocol) Depack() []string {

    Msg := make([]string, 0)

    buffer := pro.msgBuf
    BufLen := len(pro.msgBuf)
    i := 0
    for i < BufLen {
        if BufLen < i+MsgLength {
            break
        }
        msgLen := BytesToInt(buffer[i : i+MsgLength])
        if msgLen > 0 && msgLen < 2<<32 {
            if BufLen < i+MsgLength+msgLen {
                break
            }
            data := buffer[i+MsgLength : i+MsgLength+msgLen]
            Msg = append(Msg, string(data))
            i += MsgLength + msgLen
        }
    }
    if i == BufLen {
        pro.msgBuf = make([]byte, 0)
    } else {
        pro.msgBuf = buffer[i:]
    }
    return Msg
}

//IntToBytes 整形转换byte
func IntToBytes(n int) []byte {
    x := int32(n)

    bytesBuffer := bytes.NewBuffer([]byte{})
    binary.Write(bytesBuffer, binary.BigEndian, x)
    return bytesBuffer.Bytes()
}

//BytesToInt byte转换Int
func BytesToInt(b []byte) int {
    bytesBuffer := bytes.NewBuffer(b)

    var x int32
    binary.Read(bytesBuffer, binary.BigEndian, &x)
    return int(x)
}
总结:现在项目各个模块已经完成,就差一个main一个串联类,单元测试和功能性测试已经测过。但是代码整体构造太乱,没有一定的逻辑并由于对于golang语言的特性熟悉,太难写出好的代码。学以致用,使用混乱没有完美的使用这些知识,代码需要重构。暂时不给出核心代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值