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

时间:2019-03-25 08:03:57

标签: reactjs go websocket

在此先感谢您的帮助或建议!

我正在构建一个国际象棋应用程序,其前端在Reactjs中,后端是一个使用Gorilla mux库用Golang编写的服务器。后端是供人类用户使用的象棋引擎。 react前端与顶级构造函数中的服务器创建WebSocket连接。

该应用适用于单个连接。但是,在打开第二个浏览器选项卡时,第一个浏览器选项卡的Websocket连接丢失。

服务器报告错误

read error: websocket: close 1001 (going away)

然后

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

我已经查看了用于Websocket的Gorrilla / mux文档,并且正在从同一功能读取/写入所有内容,以避免在同一连接上进行并发读取或写入。

反应前端构造函数在这里:

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)
    }
  }

它引用的是websocket.js,在这里:

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

Goland Websocket软件包在这里

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)
    }
}

完整代码在这里: 伺服器:https://github.com/tonyOreglia/glee 前端:https://github.com/tonyOreglia/chess-board-react

我希望能够支持使用该网站的多个并发用户。当前托管在DigitalOcean上。

1 个答案:

答案 0 :(得分:0)

WebServer结构的设计仅允许一个连接。

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

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

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

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)
}

您还可以保留带有互斥锁的切片/地图,以存储所有连接。只是不要忘记在连接关闭时将其删除。