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

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!