doubi7346 2015-12-30 12:48
浏览 153

为什么此Go程序的websocket连接建立失败?

I am using this ip 192.168.1.55. I need to send some data to 192.168.1.137. I am using this code

package main

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

func Echo(ws *websocket.Conn) {
    fmt.Println("Echoing")

    for n := 0; n < 10; n++ {
        msg := "Hello  " + string(n+48)
        fmt.Println("Sending to client: " + msg)
        err := websocket.Message.Send(ws, msg)
        if err != nil {
            fmt.Println("Can't send")
            break
        }
    }
}

func main() {

    http.Handle("http://192.168.1.137", websocket.Handler(Echo))
    http.ListenAndServe(":4242", nil)
}

func checkError(err error) {
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
        os.Exit(1)
    }
}

But my ip is not connecting to the other ip which i have mentioned above(192.168.1.137). How to fix this?

  • 写回答

2条回答 默认 最新

  • dpfln86244 2015-12-30 13:28
    关注

    The path given for handling is wrong. You have to define the route on which the websocket should connect.

    func main() {
        http.Handle("http://192.168.1.137", websocket.Handler(Echo))
        http.ListenAndServe(":4242", nil)
    }
    

    should be

    func main() {
        http.Handle("/", websocket.Handler(Echo))
        http.ListenAndServe(":4242", nil)
    }
    

    You can use Websocket.org to test your code.

    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作