gpt4 book ai didi

api - 如何在Golang中从服务器发送Websocket

转载 作者:行者123 更新时间:2023-12-01 20:23:00 25 4
gpt4 key购买 nike

我正在尝试使用Go构建Websocket应用程序,在该应用程序中,用户输入任何字符串,然后Websocket将字符串显示回客户端(浏览器)。

但是我需要另一个可以将消息发送到websocket并将其显示在浏览器中的api(POST)。我曾尝试从类似的案例How to send the messages actively from golang's websocket server to client中学习,但仍然无法实现。

请帮我。

服务器(main.go)

package main

import (
"fmt"
"io/ioutil"
"net/http"

"github.com/gorilla/websocket"
)

type msg struct {
Input string
}

func main() {
http.HandleFunc("/ws", wsHandler)
http.HandleFunc("/", rootHandler)

panic(http.ListenAndServe(":8080", nil))
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
content, err := ioutil.ReadFile("index.html")
if err != nil {
fmt.Println("Could not open file.", err)
}
fmt.Fprintf(w, "%s", content)
}

func wsHandler(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Origin") != "http://"+r.Host {
http.Error(w, "Origin not allowed", 403)
return
}
conn, err := websocket.Upgrade(w, r, w.Header(), 1024, 1024)
if err != nil {
http.Error(w, "Could not open websocket connection", http.StatusBadRequest)
}

go echo(conn)
}

func echo(conn *websocket.Conn) {
for {
m := msg{}

err := conn.ReadJSON(&m)
if err != nil {
fmt.Println("Error reading json.", err)
}

fmt.Printf("Got message: %#v\n", m)

if err = conn.WriteJSON(m); err != nil {
fmt.Println(err)
}
}
}

客户端(index.html)
<html>
<head>
<title>WebSocket demo</title>
</head>
<body>

<div>
<form>
<label for="numberfield">Number</label>
<input type="text" id="numberfield" placeholder="12"/><br />
<button type="button" id="sendBtn">Send</button>
</form>
</div>
<div id="container"></div>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var ws;

if (window.WebSocket === undefined) {
$("#container").append("Your browser does not support WebSockets");
return;
} else {
ws = initWS();
}

function initWS() {
var socket = new WebSocket("ws://localhost:8080/ws"),
container = $("#container")
socket.onopen = function() {
container.append("<p>Socket is open</p>");
};
socket.onmessage = function (e) {
container.append("<p> Got some shit:" + e.data + "</p>");
}
socket.onclose = function () {
container.append("<p>Socket closed</p>");
}

return socket;
}

$("#sendBtn").click(function (e) {
e.preventDefault();
ws.send(JSON.stringify({ Input: $("#numberfield").val() }));
});
});
</script>
</body>
</html>

最佳答案

删除echo函数前面的“go”,无需将其作为goroutine运行。当您这样做时,它将立即关闭您的Websocket连接。我刚刚测试了一下,没有它就可以正常工作

关于api - 如何在Golang中从服务器发送Websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60018471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com