dqyl2374 2017-08-26 03:58
浏览 123
已采纳

无法在websocket.Message.Send的参数中将ccc(int类型)用作* websocket.Conn类型

I am trying to send a broadcast message to clients using websockets. How to fix this code to send message properly to all clients and without that error?

package main

import (
    "fmt"
    "golang.org/x/net/websocket"
    "net/http"
)

var connections []websocket.Conn

func main() {
    fmt.Println("vim-go")
    http.Handle("/", websocket.Handler(Server))
    err := http.ListenAndServe(":8888", nil)
    if err != nil {
        panic("ListenAndServe: " + err.Error())
    }
}

func Server(ws *websocket.Conn) {
    lll := append(connections, *ws)
    var message string
    websocket.Message.Receive(ws, &message)
    fmt.Println(message)
    for ccc := range connections {
        websocket.Message.Send(ccc, "Another connection!!!")
    }
}
  • 写回答

1条回答 默认 最新

  • duanque19820925 2017-08-26 04:52
    关注

    Not sure what you're trying to do with lll but without using it your code should not event compile.


    When rangeing over slices/arrays with a single iteration variable on the left of := it will be assigned the index of the iteration. So in your case ccc is the index.

    One thing you can do is:

    for ccc := range connections {
        websocket.Message.Send(connections[ccc], "Another connection!!!")
    }
    

    But what you probably really want is, drop the index and get the element right away which you can do using two iteration variables with the _ as the first one if you don't inted to use the index at all.

    for _, ccc := range connections {
        websocket.Message.Send(ccc, "Another connection!!!")
    }
    

    read more here: https://golang.org/ref/spec#For_range

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

报告相同问题?

悬赏问题

  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝