英文:
Why does the establishment of a websocket connection fail for this Go program?
问题
我正在使用这个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)。如何解决这个问题?
英文:
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?
答案1
得分: 1
给定的处理路径是错误的。您必须定义websocket应该连接的路由。
func main() {
http.Handle("/", websocket.Handler(Echo))
http.ListenAndServe(":4242", nil)
}
您可以使用Websocket.org来测试您的代码。
英文:
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.
答案2
得分: 0
他想要连接,而不是听。
// 你需要确保这些值是正确的,并且服务器正在监听 "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 {
log.Fatal(err)
}
for n := 0; n < 10; n++ {
msg := "Hello " + strconv.Itoa(n)
fmt.Println("发送给客户端:" + msg)
err := ws.Write([]byte(msg))
if err != nil {
fmt.Println("无法发送")
break
}
}
英文:
He wants to connect to, not to listen.
// 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 {
log.Fatal(err)
}
for n := 0; n < 10; n++ {
msg := "Hello " + strconv.Itoa(n)
fmt.Println("Sending to client: " + msg)
err := ws.Write([]byte(msg))
if err != nil {
fmt.Println("Can't send")
break
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论