drrhr20884 2012-06-11 19:03
浏览 97
已采纳

websocket发送/接收线程是否安全(执行例程安全)?

When writing a websocket server in GO (in my case using the JSON codec), is it safe to have two different Go routines for handling sending and receiving of data on the same connection?

Since websocket.JSON.Receive pauses and waits to receive data, I thought a separate Go routine for handling sending of data would be a working solution unless concurrent sending/receiving is not possible on the same connection.

So, is the working example below bad practice?

package main

import (
    "fmt"
    "net/http"
    "code.google.com/p/go.net/websocket"
)

const queueSize = 20

type Input struct {
    Cmd    string
}

type Output struct {
    Cmd    string
}

func Handler(ws *websocket.Conn) {

    msgWrite := make(chan *Output, queueSize)
    var in Input

    go writeHandler(ws, msgWrite)

    for {

        err := websocket.JSON.Receive(ws, &in)

        if err != nil {
            fmt.Println(err)
            break
        } else {
            msgWrite <- &Output{Cmd: "Thanks for your message: " + in.Cmd}
        }
    }
}

func writeHandler(ws *websocket.Conn, out chan *Output) {
    var d *Output
    for {
        select {
        case d = <-out:
            if err := websocket.JSON.Send(ws, &d); err != nil {
                fmt.Println(err.Error())
            } else {
                fmt.Println("> ", d.Cmd)
            }
        }
    }
}

func main() {
    http.Handle("/echo", websocket.Handler(Handler));
    err := http.ListenAndServe(":1235", nil);
    if err != nil {
        panic("ListenAndServe: " + err.Error())
    }
    fmt.Println("Server running")
}
  • 写回答

2条回答 默认 最新

  • dsdsds12222 2012-06-11 19:12
    关注

    Yes, you can call Send, Receive and Close on a websocket connection concurrently, like you can with all net.Conn's in Go. A short excerpt from the official docs:

    Multiple goroutines may invoke methods on a Conn simultaneously.

    Additionally, the websocket package also introduces some Codecs for sending / writing Messages or JSON data that might occupy multiple frames atomically. If you look at the source, you can see that the Send and Receive method of the Codec type will hold either the read or the write lock.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?