web123456

Golang and web end, websocket interaction

  • package main
  • import (
  • "fmt"
  • "log"
  • "net/http"
  • "strconv"
  • "time"
  • "/gorilla/websocket"
  • )
  • //Specific settings for user connection
  • type WskCon struct {
  • Name string //Generate username
  • Con * //Define the user to connect to the client
  • OnlineTime int64 //Define the user's online time in
  • }
  • //User Class
  • type Users struct {
  • cons []WskCon //Connect dataset
  • HeartTime int64 //
  • ChnCon chan * //Coop connection
  • }
  • var u *Users
  • func init() {
  • //Initialize the user class
  • s := &Users{HeartTime: 60}
  • u = s
  • }
  • func main() {
  • ("/ws", handleWebSocket)
  • ("/all", handleAll)
  • err := (":9999", nil)
  • if err != nil {
  • ("ListenAndServe: ", err)
  • }
  • }
  • //Mass message
  • func handleAll(w , r *) {
  • for _,ws:= range {
  • err := (, []byte("Send a mass message"))
  • (err)
  • }
  • ("All Connections",)
  • }
  • //Remove slice elements
  • func removeSlice(slice []WskCon, index int) []WskCon{
  • return append(slice[:index],slice[index+1:]...)
  • }
  • //Heartbeat detection
  • func heartCheck() {
  • ticker := (3*)
  • defer ()
  • for {
  • select {
  • case t := <-:
  • ("Current time: ", t, )
  • currTime := ().Unix()
  • for k, v := range {
  • // After the heartbeat time is exceeded, this data will be automatically removed, and the timeout will be 60s.
  • if (currTime - ) > {
  • //Remove the exited connection
  • = removeSlice(, k)
  • ()
  • }
  • }
  • }
  • }
  • }
  • func handleWebSocket(w , r *) {
  • // Upgrade HTTP connection to WebSocket connection
  • upgrader := {
  • ReadBufferSize: 1024,
  • WriteBufferSize: 1024,
  • // Solve cross-domain problems
  • CheckOrigin: func(r *) bool {
  • return true
  • },
  • }
  • //Check the number of connections
  • conn, err := (w, r, nil)
  • if len() >= 2 {
  • (, []byte("There are too many people connecting, please try again later"))
  • ()
  • return
  • }
  • (, []byte("Old Tie, I'm connected"))
  • //Add to the collection
  • name := (().Unix(),10)
  • = append(, WskCon{
  • Name: name,
  • Con: conn,
  • OnlineTime: ().Unix(),
  • })
  • ("all con->",)
  • if err != nil {
  • (err)
  • return
  • }
  • defer ()
  • //Detection of heartbeat
  • go heartCheck()
  • //chans := make(chan *, 2000)
  • // Looping WebSocket messages
  • for {
  • _, message, err := ()
  • if err != nil {
  • (err)
  • break
  • }
  • ("Received the message:", string(message))
  • //Send a message to update the online time
  • for k,v:= range {
  • if name == {
  • [k].OnlineTime = ().Unix()
  • }
  • }
  • // Send a message
  • err = (, message)
  • if err != nil {
  • (err)
  • break
  • }
  • }
  • }