I'm using https://github.com/googollee/go-socket.io to create a socket.io server. I'm trying to create a namespace, but I'm not able to connect to the namespace from the client side.
Server:
func registerHandlers(server *socketio.Server) {
server.Of("room1").On("connection", connectionHandler)
}
func connectionHandler(so socketio.Socket) {
log.Println("on connection")
so.Join("chat")
so.On("chat message", func(msg string) {
so.BroadcastTo("chat", "chat message", msg)
})
}
Client:
var socket = io.connect("http://localhost:3000/room1");
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
Am I missing something?
On Server side
By default socket.io works in the default namespace (/)
var io = require('socket.io')(http);
You than create namespaces from the default.
var nmspc = io.of('/namespace');
Now you can emit and receive messages within your custum namespace.
nmspc.on('connection', function(socket){
socket.on('', function(){
...
});
}
On the client side you can connect to the namespace with the following
var socket = io('/namespace').connect('http://url:PORT');
I hope this covers your question around namespaces within socket.io
You want to prefix your namespaces with a slash. The code you gave as an example would become:
func registerHandlers(server *socketio.Server) {
server.Of("/room1").On("connection", connectionHandler)
}
Give that a try.
use this sample :
package main
import (
"log"
"net/http"
"github.com/googollee/go-socket.io"
)
func main() {
server, err := socketio.NewServer(nil)
if err != nil {
log.Fatal(err)
}
// server.SetMaxConnection(9000000);
server.On("connection", func(so socketio.Socket) {
log.Println("on connection")
log.Println(so.Id())
so.On("CHAT", func(msg string) {
log.Println("CHAT +++++++>" , msg)
})
so.On("server", func(msg string) {
log.Println("serverpublic =====> " , msg)
})
so.On("disconnection", func() {
log.Println("on disconnect")
})
})
server.On("error", func(so socketio.Socket, err error) {
log.Println("error:", err)
})
http.Handle("/socket.io/", server)
log.Println("Serving at localhost:16900...")
log.Fatal(http.ListenAndServe(":15900", nil))
}//main