dsi36131 2016-12-25 09:26
浏览 33
已采纳

通过go-socked.io接收字节数组时出错

I am trying to send an Int8Array from browser to go-socked.io, here is my client's code:

function init(){
    conn = io('http://localhost:8080/');
    var c = new Int8Array([127]);
    conn.emit('m',c)
}

This is my server code

func main() {
    server, err := socketio.NewServer(nil)
    if err!= nil{
        log.Fatal(err)
    }
    server.On("connection",on_connection)
    http.Handle("/socket.io/", server)
    http.Handle("/src/", maxAgeHandler(0,http.FileServer(http.Dir("./"))))
    http.Handle("/app/", maxAgeHandler(0,http.FileServer(http.Dir("./"))))
    http.ListenAndServe(":8080",nil)
}

func on_connection(so socketio.Socket){
    log.Println("On connection")
    so.Join("Room")
    so.On("m",func(msg *socketio.Attachment){
        b, _ := ioutil.ReadAll(msg.Data)    <---- I got error in this line
        fmt.Println(b)
    })

}

The error I got said:

panic: runtime error: invalid memory address or nil pointer dereference [recovered]
    panic: runtime error: invalid memory address or nil pointer dereference

I would like to know how to read the byte data in the message.

  • 写回答

1条回答 默认 最新

  • dongwen5336 2016-12-25 23:20
    关注

    You aren't sending an attachment, just data. This data can be used mapped with map[string]int8 because you're sending an array of int8 and this is translated as a map in socketio.

    func on_connection(so socketio.Socket) {
        log.Println("On connection")
        so.Join("Room")
        so.On("m", func(data map[string]int8) {
            array := make([]int8, len(data))
            for k, v := range data {
                pos, _ := strconv.Atoi(k)
                array[pos] = v
            }
            fmt.Println(array)
        })
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退