为什么这个Go程序建立websocket连接失败?

我正在使用这个 ip 192.168.1.55。我需要向 192.168.1.137 发送一些数据。我正在使用此代码


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)

    }

}

但是我的 ip 没有连接到我上面提到的另一个 ip (192.168.1.137)。如何解决这个问题?


万千封印
浏览 282回答 2
2回答

largeQ

给出的处理路径是错误的。您必须定义 websocket 应该连接的路由。func main() {&nbsp; &nbsp; http.Handle("http://192.168.1.137", websocket.Handler(Echo))&nbsp; &nbsp; http.ListenAndServe(":4242", nil)}应该func main() {&nbsp; &nbsp; http.Handle("/", websocket.Handler(Echo))&nbsp; &nbsp; http.ListenAndServe(":4242", nil)}您可以使用Websocket.org来测试您的代码。

Smart猫小萌

他想连接,而不是倾听。// you need to make sure this values are correct. and server is listening on "192.168.1.137:4242"origin := "http://192.168.1.55/"url := "ws://192.168.1.137:4242"ws, err := websocket.Dial(url, "", origin)if err != nil {&nbsp; &nbsp; log.Fatal(err)}for n := 0; n < 10; n++ {&nbsp; &nbsp; msg := "Hello&nbsp; " + strconv.Itoa(n)&nbsp; &nbsp; fmt.Println("Sending to client: " + msg)&nbsp; &nbsp; err := ws.Write([]byte(msg))&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Can't send")&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go