我正在尝试与用 Go 和 JavaScript 前端编写的服务器建立 websocket 连接。我在一个目录中有以下文件:
main.go 索引.html
**这是我的 Go 代码main.go:**
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func homePage(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./index.html")
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("Error in handler:", err)
return
}
log.Println("Client connected.")
for {
messageType, p, err := conn.ReadMessage()
if err != nil {
log.Println("Fehler in ReadMessage: ", err)
return
}
log.Println(string(p))
//echo message to client
if err := conn.WriteMessage(messageType, p); err != nil {
log.Println(err)
return
}
}
}
func setupRoutes() {
http.HandleFunc("/ws", homePage)
}
func main() {
fmt.Println("Server gestartet")
setupRoutes()
log.Fatal(http.ListenAndServe(":9100", nil))
}
这是 index.html 中的 HTML 和 JavaScript:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Some unimportant html </title>
</head>
<body>
<script>
let socket = new WebSocket("ws://localhost:9100/ws");
console.log("Websocket started.");
socket.onOpen = () => {
console.log("Client started.");
}
socket.onclose = (event) => {
console.log("Socket closed: ", event);
}
socket.onError = (error) => {
console.log("Socket Error: ", error);
}
socket.onMessage = (msg) => {
console.log(msg);
}
</script>
</body>
</html>
胡子哥哥
相关分类