如何使用Golang Gorilla / mux托管并发Websocket连接?

thanks in advance for any help or advice!

I am building a chess application, the frontend is in Reactjs and backend is a server written in Golang using Gorilla mux library. The backend is a chess engine for the human user to play against. The react frontend creates a WebSocket connection with the server in the top-level constructor.

The app works well for a single connection. However, upon opening a second browser tab, the first browser tab's Websocket connection is lost.

The server reports the error,

read error: websocket: close 1001 (going away)

and then,

read error: read tcp 127.0.0.1:8081-\u003e127.0.0.1:64146: use of closed network connection

I've looked at the Gorrilla/mux documentation for websockets and am reading/writing all from the same function in order to avoid concurrent reads or writes on the same connection.

React frontend constructor is here:

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [{
        position: this.props.chess.fen(),
        move: "",
      }],
      ply: 0,
      selectedSq: null,
      engineName: "",
      engineAuthor: "",
      uciOK: false,
      isReady: false,
      engineThinking: false,
      playersTurn: true,
      playerColor: WHITE,
    };
    this.ws = websocketConnect("ws://localhost:8081/uci");
    this.ws.onmessage = (event) => {
      const msg = event.data
      this.processEngineMessage(msg)
    }
  }

It is referencing websocket.js which is here:

export function websocketConnect(url) {
  const ws = new WebSocket(url);
  ws.addEventListener('open', (event) => {
    ws.send('uci');
  });
  return ws;
}

Goland Websocket package is here

package websocket

import (
    "net/http"

    "github.com/namsral/flag"
    log "github.com/sirupsen/logrus"

    "github.com/gorilla/websocket"
)

type WebsocketServer struct {
    upgrader websocket.Upgrader
    addr     *string
    conn     *websocket.Conn
}

func NewWebsocketServer() *WebsocketServer {
    w := new(WebsocketServer)
    w.addr = flag.String("addr", "localhost:8081", "http service address")
    flag.Parse()
    w.upgrader = websocket.Upgrader{} // use default options
    http.HandleFunc("/uci", w.uciHandler)
    return w
}

func (w *WebsocketServer) uciHandler(rw http.ResponseWriter, r *http.Request) {
    var err error
    log.Error("upgrading to websocket connection")
    w.upgrader.CheckOrigin = func(r *http.Request) bool { return true }
    w.conn, err = w.upgrader.Upgrade(rw, r, nil)
    if err != nil {
        log.Print("upgrade:", err)
        return
    }
    go w.UCI(rw, r)
}

func (w *WebsocketServer) Start() {
    log.Info("starting websocket server")
    http.ListenAndServe(*w.addr, nil)
}

func (w *WebsocketServer) CloseConnection() {
    w.conn.Close()
}

func (w *WebsocketServer) StartReader(channel chan string) {
    for {
        _, message, err := w.conn.ReadMessage()
        if err != nil {
            log.Println("read error:", err)
            break
        }
        log.Printf("recv: %s", message)
        channel <- string(message)
    }
}

func (w *WebsocketServer) Write(msg string) {
    err := w.conn.WriteMessage(websocket.TextMessage, []byte(msg))
    if err != nil {
        log.Println("write:", err)
    }
}

Full code here: server: https://github.com/tonyOreglia/glee frontend: https://github.com/tonyOreglia/chess-board-react

I am hoping to be able to support multiple concurrent users using the website. It is currently hosted on DigitalOcean.

1个回答



WebServer </ code>结构的设计仅允许单个连接。 </ p>

发生的情况是,在 / uci </ code>上的每个初始HTTP请求上,连接都被替换,并且每次将http请求升级为ws连接时,都将替换 该服务器在 WebServer </ code>结构上的先前连接。 </ p>

此外,它也不是线程安全的,因为每个请求都是在不同的goroutine中处理的。</ p>

我建议您将连接传递给 UCI </ code>方法,而不是将其附加到服务器。 </ p>

  type WebsocketServer struct {
upgrader websocket.Upgrader
addr * string
}

func(w * WebsocketServer )uciHandler(rw​​ http.ResponseWriter,r * http.Request){
var err error
log.Error(“升级到websocket连接”)
w.upgrader.CheckOrigin = func(r * http.Request)bool {return true}
//这就是区别
conn,err:= w.upgrader.Upgrade(rw,r,nil)
如果err!= nil {
log.Print(“ upgrade:”, err)
return
}
//然后在这里
去w.UCI(rw,r,conn)
}
</ code> </ pre>

使用互斥锁保存切片/地图,以存储所有连接。 只是不要忘记在连接关闭时将其删除。</ p>
</ div>

展开原文

原文

The design of your WebServer struct only allows for a single connection.

What happens is that on every initial http request on /uci, the connection get upgaded, and everytime you upgrade the http request to a ws connection, you replace the previous connection on the WebServer struct by that one.

Also, it is not thread safe, as each request is processed in a different goroutine.

I suggest you pass the connection to your UCI method instead of attaching it to the server.

type WebsocketServer struct {
    upgrader websocket.Upgrader
    addr     *string
}

func (w *WebsocketServer) uciHandler(rw http.ResponseWriter, r *http.Request) {
    var err error
    log.Error("upgrading to websocket connection")
    w.upgrader.CheckOrigin = func(r *http.Request) bool { return true }
    // here is the difference
    conn, err := w.upgrader.Upgrade(rw, r, nil)
    if err != nil {
        log.Print("upgrade:", err)
        return
    }
    // and here
    go w.UCI(rw, r, conn)
}

You could also keep a slice/map with a mutex where you store all your connections. Just don't forget to remove it when your connection closes.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问