go-socket.io
go-socket.io copied to clipboard
[BUG] OnEvent error:websocket: write closed
Describe the bug server.OnEvent("signaling", "Register”, func(so socketio.Conn, msg interface{}) I use the method of OnEvent like above,.but it always happen this: meet error:websocket: write closed
I try to add heart beat each 1 second,It doesn't work.
@zhouruisong Hi It is difficult understand your issue. Please share some example code about your problem.
It is work. Interface between client and server in Go-socket.io work as origin socket.io protocol.
Correct code:
server.OnEvent("/signaling", "Register", func(s socketio.Conn, msg interface{})
Full text code:
Client code:
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
var s2 = io("/signaling");
socket.on('reply', function(msg){
$('#messages').append($('<li>').text(msg));
});
$('form').submit(function(){
s2.emit('Register', $('#m').val(), function(data){
$('#messages').append($('<li>').text('ACK CALLBACK: ' + data));
});
socket.emit('notice', $('#m').val());
$('#m').val('');
return false;
});
</script>
</body>
</html>
Server code:
package main
import (
"fmt"
"log"
"net/http"
socketio "github.com/googollee/go-socket.io"
)
func main() {
server, err := socketio.NewServer(nil)
if err != nil {
log.Fatal(err)
}
server.OnConnect("/", func(s socketio.Conn) error {
s.SetContext("")
fmt.Println("connected:", s.ID())
return nil
})
server.OnEvent("/", "notice", func(s socketio.Conn, msg string) {
fmt.Println("notice:", msg)
s.Emit("reply", "have "+msg)
})
server.OnEvent("/signaling", "Register", func(s socketio.Conn, msg string) string {
s.SetContext(msg)
return "recv " + msg
})
server.OnEvent("/", "bye", func(s socketio.Conn) string {
last := s.Context().(string)
s.Emit("bye", last)
s.Close()
return last
})
server.OnError("/", func(e error) {
fmt.Println("meet error:", e)
})
server.OnDisconnect("/", func(s socketio.Conn, msg string) {
fmt.Println("closed", msg)
})
go server.Serve()
defer server.Close()
http.Handle("/socket.io/", server)
http.Handle("/", http.FileServer(http.Dir("../asset")))
log.Println("Serving at localhost:8000...")
log.Fatal(http.ListenAndServe(":8000", nil))
}