douzhanrun0497 2016-12-21 08:28
浏览 159

使用Golang扩展WebSocket连接

   func handleConn(w http.ResponseWriter, r *http.Request) {
        ws, err := upgrader.Upgrade(w, r, nil)
        if err != nil {
            if _, ok := err.(websocket.HandshakeError); !ok {
                log.Println(err)
            }
            return
       }

        go writer(ws)
        reader(r, ws)
    }

    func main() {
       http.HandleFunc("/", handleConn)
    }

I am trying to build a high scaling websocket server using golang. Since there is lack of support in native go websocket package, i am using https://github.com/gorilla/websocket.

For every connection, a goroutine will be spawned to take care of writes to it. For scaling huge number of connections. Let's say if I have 1M concurrent connections then there should be 1M goroutines will be running on the server.

Hardware Specification:

16 GB Ram

4 Core CPU

2.5 GHz Intel Core i5

will it work for large number of connections without affecting the performance?

  • 写回答

1条回答 默认 最新

  • doujie3888 2018-07-23 16:27
    关注

    Lets do some mathematics:

    Theoretically: Each go-routine consumes 8KB of memory. So, for a million sockets, 8GB of ram is required.

    Now, let's shift the paradigm towards practicality. Since, you are using web socket, you are looking for two way channel communication. So, you would have to reserve a buffer for reading data from each socket. So, another 8 GB of RAM gone just for listening the data from socket. These figures just denotes the resource, required to spin and spawn a million connections, and doesn't include other important factors (resource reserved for other tasks, kernel reserved space, OS reserved space, etc.)

    Conclusion: This approach is simple, but not scalable beyond a certain limit.

    You would definitely need much more RAM, to scale at the proposed figure.

    You can minimise the memory consumption by implementing something like kQueue/ePoll. Via this approach, instead of constantly waiting for data to be consumed, and wasting the buffer memory, you would implement a callback, which gets informed if the socket is ready to read/write data, and then you can create a buffer and do read/write operations over the file descriptor. This would help you reuse the buffer, and thereby reduce resource consumption.

    Hope that helps!

    评论

报告相同问题?

悬赏问题

  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上