name5566 / leaf

A game server framework in Go (golang)
Apache License 2.0
5.26k stars 1.31k forks source link

例子中服务端回给客户端的信息,客户端要如何才能收到啊 #174

Closed widon1104 closed 4 years ago

widon1104 commented 4 years ago

TUTORIAL中 服务端在最后要给客户端回一个消息 func handleHello(args []interface{}) { .... // 给发送者回应一个 Hello 消息 a.WriteMsg(&msg.Hello{ Name: "client", }) } Hello的定义: syntax = "proto3"; package main;
message Hello {
string name = 1;
}

但是客户端只是发送了消息,并没有收服务端发送回他的消息 // 发送消息 conn.Write(m)

客户端要怎么样写代码才能收到服务端回给他的消息呢?

widon1104 commented 4 years ago

` conn.Write(m)

var buf = make([]byte, 128)
for {
    n, err := conn.Read(buf)
    if err != nil {
        fmt.Println("Read error", err)
        break
    }
    if n == 0 {
        fmt.Println("连接已经关闭")
        break
    }
    buf = buf[:n]
    a := &Hello{}
    err = proto.Unmarshal(buf[:n], a)
    if err != nil {
        fmt.Println("unmarshal error: ", err)
        break
    }
    fmt.Println(a)
}`

我用上面这个代码,老是报 widon@widon-ubuntu:~/golang/src/leafclient$ ./leafclient unmarshal error: proto: main.Hello: illegal tag 0 (wire type 0)

widon1104 commented 4 years ago

我知道了 err = proto.Unmarshal(buf[4:n], a)

Unmarshal的时候需要从第5个字节开始,以为前4个字节是len和id