英文:
Error in Receiving byte array via go-socked.io
问题
我正在尝试将一个 Int8Array 从浏览器发送到 go-socked.io,这是我的客户端代码:
function init(){
conn = io('http://localhost:8080/');
var c = new Int8Array([127]);
conn.emit('m', c);
}
这是我的服务器代码:
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)
})
}
我得到的错误信息是:
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference
我想知道如何读取消息中的字节数据。
英文:
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
得分: 0
你没有发送附件,只是发送了数据。这些数据可以使用map[string]int8
进行映射,因为你发送的是int8数组,而在socketio中,它被翻译为一个map。
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)
})
}
英文:
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.
<!-- language: go -->
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)
})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论