Websocket关闭得非常快。

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

Websocket closed very quickly

问题

我正在尝试这个WebSocket示例:

package main

import (
	"fmt"
	"log"
	"net/http"

	"golang.org/x/net/websocket"
)

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("/", websocket.Handler(Echo))

	if err := http.ListenAndServe(":1234", nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}

使用以下客户端:

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

        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>

但是出现了以下错误:
Websocket关闭得非常快。

英文:

I'm trying this websocket example:

package main

import (
	&quot;fmt&quot;
	&quot;log&quot;
	&quot;net/http&quot;

	&quot;golang.org/x/net/websocket&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)
	}
}

With this client:

&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://localhost: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;

But getting the below error:
Websocket关闭得非常快。

答案1

得分: 0

我在使用标准库的websocket时遇到了麻烦,所以像大多数Go开发者一样,我使用了Gorilla websocket包。你可以尝试使用以下代码(基于我的工作代码):

package main

import (
    "log"
    "net/http"
    "github.com/gorilla/websocket"
)

func echo(w http.ResponseWriter, r *http.Request) {
    conn, err := websocket.Upgrade(w, r, w.Header(), 1024, 1024)
    if err != nil {
        http.Error(w, "Could not open websocket connection", http.StatusBadRequest)
        return
    }
    for {
        messageType, message, err := conn.ReadMessage()
        if err != nil {
            log.Println("read:", err)
            break
        }
        log.Printf("recv: %s", message)
        err = conn.WriteMessage(messageType, message)
        if err != nil {
            log.Println("write:", err)
            break
        }
    }
}

func main() {
    http.HandleFunc("/", echo)

    if err := http.ListenAndServe(":1234", nil); err != nil {
        log.Fatal("ListenAndServe:", err)
    }
}

我认为你会通过这种方式获得更多乐趣。

英文:

I had trouble with std lib webscokets and (like most Go people) use Gorilla websocket package. Try this code (based on my working code):

package main
import (
&quot;log&quot;
&quot;net/http&quot;
&quot;github.com/gorilla/websocket&quot;
)
func echo(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Upgrade(w, r, w.Header(), 1024, 1024)
if err != nil {
http.Error(w, &quot;Could not open websocket connection&quot;, http.StatusBadRequest)
return
}
for {
messType, message, err := conn.ReadMessage()
if err != nil {
log.Println(&quot;read:&quot;, err)
break
}
log.Printf(&quot;recv: %s&quot;, message)
err = conn.WriteMessage(messType, message)
if err != nil {
log.Println(&quot;write:&quot;, err)
break
}
}
}
func main() {
http.HandleFunc(&quot;/&quot;, echo)
if err := http.ListenAndServe(&quot;:1234&quot;, nil); err != nil {
log.Fatal(&quot;ListenAndServe:&quot;, err)
}
}

I think you'll have a lot more joy this way.

huangapple
  • 本文由 发表于 2022年6月11日 21:31:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/72584769.html
匿名

发表评论

匿名网友

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

确定