Initial Version
Create a module
Run the go mod init
command, giving it the path of the module your code will be in.
go mod init literank.com/webchat
Its result:
go: creating new go.mod: module literank.com/webchat
This command creates a go.mod
file in which dependencies you add will be listed for tracking.
Installation
Download and install socket.io
library:
go get -u github.com/zishang520/socket.io/v2
We don't use github.com/googollee/go-socket.io here because it currently only supports 1.4 version of the Socket.IO client.
The latest version of Socket.IO is 4.x.
This command updates the go.mod
file and creates a go.sum
file in your project.
Create main.go:
package main
import (
"fmt"
"net/http"
"github.com/zishang520/engine.io/v2/types"
"github.com/zishang520/socket.io/v2/socket"
)
const port = 4000
func main() {
// CORS
opts := &socket.ServerOptions{}
opts.SetCors(&types.Cors{Origin: "*"})
io := socket.NewServer(nil, opts)
io.On("connection", func(clients ...any) {
client := clients[0].(*socket.Socket)
fmt.Println("A user connected:", client.Id())
})
http.Handle("/socket.io/", io.ServeHandler(nil))
fmt.Printf("Chat server serving at localhost:%d...\n", port)
http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}
Run the program like this:
go run main.go
You will get a result line like this:
Chat server serving at localhost:4000...
Your chat server is running on port 4000 now.