dongpa2000 2018-08-06 01:07
浏览 148
已采纳

在Websocket中使用频道

If I use a chan anywhere on main or func home, the application runs, but it doesn't really work. No errors thrown, however, it won't work. If I remove the channels references, it goes back to working. Either by using a chan in a struct or a global channel the application stops working.

In a GET request, it returns h.Message from func home by adding any channel in the code, GET request wont return the message.

https://play.golang.org/p/-ZVcLhZRRRG

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/websocket"
    // _ "github.com/go-sql-driver/mysql"
)

type WMessage struct {
    Message string `json:"message"`
    ch      chan string
}

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

var Chann chan string

func (h *WMessage) home(w http.ResponseWriter, r *http.Request) {
    h.Message = "hey this is the message from home"

    fmt.Fprintln(w, h.Message)
    fmt.Println(<-h.ch)
}

func main() {
    hom := &WMessage{}

    hom.ch = make(chan string)

    hom.ch <- "message sent"

    http.HandleFunc("/", hom.home)
    err := http.ListenAndServe(":3000", nil)
    if err != nil {
        fmt.Println("there was an error -> ", err)
    }
}
  • 写回答

1条回答 默认 最新

  • douduiti3040 2018-08-06 04:11
    关注

    Unbuffered channels are blocking in nature, i.e. writing to channel (hom.ch <- "message sent") and reading from channel (fmt.Println(<-h.ch)) block the go-routine.

    In your case, http server is not running because hom.ch <- "message sent" blocks the execution. That's why GET request is not working.

    One simple solution can be to make it buffered channel instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图