Skip to content

Instantly share code, notes, and snippets.

@supanadit
Created January 4, 2020 23:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save supanadit/f6de65fc5896e8bb0c4656e451387d0f to your computer and use it in GitHub Desktop.
Save supanadit/f6de65fc5896e8bb0c4656e451387d0f to your computer and use it in GitHub Desktop.
Gin Gonic + Socket IO
package main
import (
"fmt"
"github.com/gin-gonic/gin"
engineio "github.com/googollee/go-engine.io"
"github.com/googollee/go-engine.io/transport"
engineiopooling "github.com/googollee/go-engine.io/transport/polling"
socketio "github.com/googollee/go-socket.io"
"log"
"net/http"
"time"
)
func main() {
// Use Transport Pooling, because Websocket Transport still Error
server, err := socketio.NewServer(&engineio.Options{
Transports: []transport.Transport{
&engineiopooling.Transport{
Client: &http.Client{
Timeout: time.Minute,
},
},
},
})
if err != nil {
log.Fatal(err)
}
server.OnConnect("/", func(s socketio.Conn) error {
s.SetContext("")
fmt.Println("Connected:", s.ID())
return nil
})
server.OnEvent("/", "msg", func(s socketio.Conn, msg string) string {
fmt.Println("Receive Message : " + msg)
s.Emit("reply", "OK")
return "recv " + msg
})
server.OnDisconnect("/", func(s socketio.Conn, msg string) {
fmt.Println("Somebody just close the connection ")
})
go server.Serve()
defer server.Close()
// Create Setup
router := gin.Default()
// Combine Gin Gonic with Socket IO
// Method 1 using gin.WrapH or you changes this with server.ServeHTTP(Writer, Request)
router.GET("/socket.io/", gin.WrapH(server))
// Method 2 using server.ServerHTTP(Writer, Request) and also you can simply this by using gin.WrapH
router.POST("/socket.io/", func(context *gin.Context) {
server.ServeHTTP(context.Writer, context.Request)
})
// Run Gin
_ = router.Run(":8080")
}
@eldonwilliams
Copy link

That you for this!

@ptflp
Copy link

ptflp commented Feb 25, 2023

not working with new socket io version API

@shantanoo
Copy link

not working with new socket io version API

Latest supported version seems to be 1.4.x of socketio. 2.x is not supported.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment