使用Golang服务器直接创建WebSocket连接的静态HTML页面。

huangapple go评论85阅读模式
英文:

Static html page created the WebSocket connection golang server directly

问题

我正在编写一个需要创建到服务器的websocket的html页面。

在服务器上,我使用了code.google.com/p/go.net/websocket中的示例来接受连接。

然而,在Chrome26中,响应是

WebSocket连接到'ws://127.0.0.1:1234/'失败:意外的响应代码:400

有什么我漏掉的东西(比如握手)吗?

这是我的html,服务器使用的是go语言

<html>
<head></head>
<body>
<script type="text/javascript">
    var sock = null;
    var wsuri = "ws://127.0.0.1:1234";

    window.onload = function() {

        console.log("onload");

        sock = new WebSocket(wsuri);

        sock.onopen = function() {
            console.log("connected to " + wsuri);
        }

        sock.onclose = function(e) {
            console.log("connection closed (" + e.code + ")");
        }

        sock.onmessage = function(e) {
            console.log("message received: " + e.data);
        }
    };

    function send() {
        var msg = document.getElementById('message').value;
        sock.send(msg);
    };
</script>
<h1>WebSocket Echo Test</h1>
<form>
    <p>
        Message: <input id="message" type="text" value="Hello, world!">
    </p>
</form>
<button onclick="send();">Send Message</button>
</body>
</html>
package main

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

func Echo(ws *websocket.Conn) {
    var err error

    for {
        var reply string

        if err = websocket.Message.Receive(ws, &reply); err != nil {
            fmt.Println("Can't receive")
            break
        }

        fmt.Println("Received back from client: " + reply)

        msg := "Received:  " + reply
        fmt.Println("Sending to client: " + msg)

        if err = websocket.Message.Send(ws, msg); err != nil {
            fmt.Println("Can't send")
            break
        }
    }
}

func main() {
    http.Handle("/", websocket.Handler(Echo))
    if err := http.ListenAndServe(":1234", nil); err != nil {
        log.Fatal("ListenAndServe:", err)
    }
}
英文:

I'm writing an html page that needs to create a websocket to the server

On the server, I used the example in "code.google.com/p/go.net/websocket" just accept the connection.

However, in Chrome26 the response is

WebSocket connection to 'ws://127.0.0.1:1234/' failed: Unexpected response code: 400

Is there something is missed (like a handshake)?

This is my html and server is using go

&lt;html&gt;
&lt;head&gt;&lt;/head&gt;
&lt;body&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
    var sock = null;
    var wsuri = &quot;ws://127.0.0.1:1234&quot;;

    window.onload = function() {

        console.log(&quot;onload&quot;);

        sock = new WebSocket(wsuri);

        sock.onopen = function() {
            console.log(&quot;connected to &quot; + wsuri);
        }

        sock.onclose = function(e) {
            console.log(&quot;connection closed (&quot; + e.code + &quot;)&quot;);
        }

        sock.onmessage = function(e) {
            console.log(&quot;message received: &quot; + e.data);
        }
    };

    function send() {
        var msg = document.getElementById(&#39;message&#39;).value;
        sock.send(msg);
    };
&lt;/script&gt;
&lt;h1&gt;WebSocket Echo Test&lt;/h1&gt;
&lt;form&gt;
    &lt;p&gt;
        Message: &lt;input id=&quot;message&quot; type=&quot;text&quot; value=&quot;Hello, world!&quot;&gt;
    &lt;/p&gt;
&lt;/form&gt;
&lt;button onclick=&quot;send();&quot;&gt;Send Message&lt;/button&gt;
&lt;/body&gt;
&lt;/html&gt;

//------------------------------

package main

import (
	&quot;code.google.com/p/go.net/websocket&quot;
	&quot;fmt&quot;
	&quot;log&quot;
	&quot;net/http&quot;
)

func Echo(ws *websocket.Conn) {
	var err error

	for {
		var reply string

		if err = websocket.Message.Receive(ws, &amp;reply); err != nil {
			fmt.Println(&quot;Can&#39;t receive&quot;)
			break
		}

		fmt.Println(&quot;Received back from client: &quot; + reply)

		msg := &quot;Received:  &quot; + reply
		fmt.Println(&quot;Sending to client: &quot; + msg)

		if err = websocket.Message.Send(ws, msg); err != nil {
			fmt.Println(&quot;Can&#39;t send&quot;)
			break
		}
	}
}

func main() {
	http.Handle(&quot;/&quot;, websocket.Handler(Echo))
	if err := http.ListenAndServe(&quot;:1234&quot;, nil); err != nil {
		log.Fatal(&quot;ListenAndServe:&quot;, err)
	}
}

答案1

得分: 5

Chrome可能会抛出400错误,因为它认为您正在尝试对websocket服务器进行跨域请求,并认为您可能没有权限。

要解决此问题,您只需从您的go服务器上提供html。

所以将您的sock.go代码更改为:

package main

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

func Echo(ws *websocket.Conn) {
    var err error

    for {
        var reply string

        if err = websocket.Message.Receive(ws, &reply); err != nil {
            fmt.Println("无法接收")
            break
        }

        fmt.Println("从客户端接收到的消息:" + reply)

        msg := "接收到的消息:" + reply
        fmt.Println("发送给客户端的消息:" + msg)

        if err = websocket.Message.Send(ws, msg); err != nil {
            fmt.Println("无法发送")
            break
        }
    }
}

func main() {
    http.Handle("/", http.FileServer(http.Dir("."))) // <-- 注意这一行
    http.Handle("/socket", websocket.Handler(Echo))
    log.Println("服务中")
    if err := http.ListenAndServe(":1234", nil); err != nil {
        log.Fatal("ListenAndServe:", err)
    }
}

并将您的index.html文件添加到与sock.go文件相同的目录中:

<html>
<head></head>
<body>
<script type="text/javascript">
    var sock = null;
    var wsuri = "ws://127.0.0.1:1234/socket"; // <-- 注意新的路径

    window.onload = function() {

        console.log("onload");

        sock = new WebSocket(wsuri);

        sock.onopen = function() {
            console.log("已连接到" + wsuri);
        }

        sock.onclose = function(e) {
            console.log("连接已关闭(" + e.code + ")");
        }

        sock.onmessage = function(e) {
            console.log("收到消息:" + e.data);
        }
    };

    function send() {
        var msg = document.getElementById('message').value;
        sock.send(msg);
    };
</script>
<h1>WebSocket Echo测试</h1>
<form>
    <p>
        消息:<input id="message" type="text" value="Hello, world!">
    </p>
</form>
<button onclick="send();">发送消息</button>
</body>
</html>

现在您将能够在Chrome中进行连接。

英文:

Chrome is likely throwing error 400 because it thinks you are trying to do a cross-domain request to the websocket server and thinks it is unlikely you have permission.

To solve the issue you simply have to server your html from your go-server too.

So change your sock.go code to:

package main

import (
	&quot;code.google.com/p/go.net/websocket&quot;
	&quot;fmt&quot;
	&quot;log&quot;
	&quot;net/http&quot;
)

func Echo(ws *websocket.Conn) {
	var err error

	for {
		var reply string

		if err = websocket.Message.Receive(ws, &amp;reply); err != nil {
			fmt.Println(&quot;Can&#39;t receive&quot;)
			break
		}

		fmt.Println(&quot;Received back from client: &quot; + reply)

		msg := &quot;Received:  &quot; + reply
		fmt.Println(&quot;Sending to client: &quot; + msg)

		if err = websocket.Message.Send(ws, msg); err != nil {
			fmt.Println(&quot;Can&#39;t send&quot;)
			break
		}
	}
}

func main() {
	http.Handle(&quot;/&quot;, http.FileServer(http.Dir(&quot;.&quot;))) // &lt;-- note this line
	http.Handle(&quot;/socket&quot;, websocket.Handler(Echo))
	log.Println(&quot;serving&quot;)
	if err := http.ListenAndServe(&quot;:1234&quot;, nil); err != nil {
		log.Fatal(&quot;ListenAndServe:&quot;, err)
	}
}

and add your index.html file to the same directory as your sock.go file:

&lt;html&gt;
&lt;head&gt;&lt;/head&gt;
&lt;body&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
    var sock = null;
    var wsuri = &quot;ws://127.0.0.1:1234/socket&quot;; // &lt;-- note new path

    window.onload = function() {

        console.log(&quot;onload&quot;);

        sock = new WebSocket(wsuri);

        sock.onopen = function() {
            console.log(&quot;connected to &quot; + wsuri);
        }

        sock.onclose = function(e) {
            console.log(&quot;connection closed (&quot; + e.code + &quot;)&quot;);
        }

        sock.onmessage = function(e) {
            console.log(&quot;message received: &quot; + e.data);
        }
    };

    function send() {
        var msg = document.getElementById(&#39;message&#39;).value;
        sock.send(msg);
    };
&lt;/script&gt;
&lt;h1&gt;WebSocket Echo Test&lt;/h1&gt;
&lt;form&gt;
    &lt;p&gt;
        Message: &lt;input id=&quot;message&quot; type=&quot;text&quot; value=&quot;Hello, world!&quot;&gt;
    &lt;/p&gt;
&lt;/form&gt;
&lt;button onclick=&quot;send();&quot;&gt;Send Message&lt;/button&gt;
&lt;/body&gt;
&lt;/html&gt;

Now you will be able to connect from within chrome.

huangapple
  • 本文由 发表于 2013年4月9日 00:40:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/15884480.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定