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

静态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.

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!