func main() {
l, err := net.Listen("tcp", ":8095")
if err != nil {
log.Fatal(err)
}
defer func(l net.Listener) {
err := l.Close()
if err != nil {
}
}(l)
fmt.Println("init success ........")
for {
conn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
//go handleMsg(conn)
buff := make([]byte, 1024)
msg := ""
for {
n, err := conn.Read(buff)
if err != nil {
return
}
s := string(buff[:n])
msg = msg + s
// msg = msg+string(buff[:n])
//fmt.Print(string(buff[:n]))
}
}
}
代码大概是这样的
其中bus是个解耦用的总线
```
func (conn *Conn) Receiver(bus *bus.Bus) {
del := byte(10)
del2 := byte(13)
for {
running := conn.Connected(bus)
if !running {
return
}
s, err := conn.telnet.ReadByte()
if err != nil {
if !isClosedError(err) {
bus.HandleConnError(err)
}
conn.Lock.Lock()
if conn.running == true {
go bus.RaiseServerCloseEvent()
}
conn.Lock.Unlock()
conn.Close(bus)
return
}
conn.Lock.Lock()
if s == del2 {
conn.Lock.Unlock()
continue
}
if s == del {
if err != nil {
conn.Lock.Unlock()
bus.HandleConnError(err)
return
}
conn.flushBuffer(bus)
continue
}
conn.buffer = append(conn.buffer, s)
if bus.HandleBuffer(conn.buffer) {
conn.flushBuffer(bus)
continue
}
conn.Lock.Unlock()
conn.Debounce.Exec()
}
}
```
处理数据的是 conn.flushBuffer
代码是
```
func (conn *Conn) flushBuffer(bus *bus.Bus) {
buf := conn.buffer
conn.Debounce.Reset()
conn.buffer = []byte{}
conn.Lock.Unlock()
bus.HandleConnReceive(buf)
}
```
#5
更多评论
![iShot2021-12-23 09.58.05.png](https://static.studygolang.com/211223/9890f9194b579b43f46b27498e2c4aca.png)
#1