dsce23640 2013-04-08 16:40
浏览 171
已采纳

静态html页面直接创建了WebSocket连接golang服务器

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

<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)
    }
}
  • 写回答

1条回答 默认 最新

  • duannuochi3549 2013-04-08 17:12
    关注

    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 (
        "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("/", http.FileServer(http.Dir("."))) // <-- note this line
        http.Handle("/socket", websocket.Handler(Echo))
        log.Println("serving")
        if err := http.ListenAndServe(":1234", nil); err != nil {
            log.Fatal("ListenAndServe:", err)
        }
    }
    

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

    <html>
    <head></head>
    <body>
    <script type="text/javascript">
        var sock = null;
        var wsuri = "ws://127.0.0.1:1234/socket"; // <-- note new path
    
        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>
    

    Now you will be able to connect from within chrome.

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

报告相同问题?

悬赏问题

  • ¥15 MATLAB怎么通过柱坐标变换画开口是圆形的旋转抛物面?
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿