实时应用程序最有效的策略之一是使用 WebSocket 协议。
WebSocket 是一种计算机通信协议,通过单个传输控制协议(TCP)连接提供同步双向通信通道。为了实现兼容性,WebSocket 握手使用 HTTP Upgrade header[3] 从 HTTP 协议转换到 WebSocket 协议。
虽然完全可以将连接从基本的 net/http 连接处理程序升级为 WebSocket 风格连接,但我们将使用 gorilla/websocket Go 模块。通过 Go 模块,我们只需几行简单的 Go 代码就能创建 WebSocket 服务器。
第一步:安装 gorilla/websocket 模块
go get github.com/gorilla/websocket
第二步:创建 HTTP 端点
package main
import (
"net/http"
"github.com/gorilla/websocket"
"fmt"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
// HTTP Handler for localhost:8080/ws
})
fmt.Println("Server Started Successfully")
if err := http.ListenAndServe("localhost:8080", mux); err != nil {
panic(err)
}
}
第三步:升级连接
package main
import (
"net/http"
"github.com/gorilla/websocket"
"fmt"
)
// Create a connection upgrader
var upgrader websocket.Upgrader = websocket.Upgrader{}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
panic(err)
}
// Defer Closing the connection
defer conn.Close()
// ...
})
fmt.Println("Server Started Successfully")
if err := http.ListenAndServe("localhost:8080", mux); err != nil {
panic(err)
}
}
第四步:使用 for 循环捕捉信息
// This section is the same file as above, just shortened to our handler
mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
panic(err)
}
// Defer Closing the connection
defer conn.Close()
// Use a for loop to catch incoming messages.
for {
// msgType = int msg type
// p = incoming message as []byte
// err = error on message
msgType, p, err := conn.ReadMessage()
if err != nil {
fmt.Println("Error reading message")
return
}
// Once we recieve a message, we can echo it back.
err = conn.WriteMessage(msgType, p)
if err != nil {
fmt.Println("Error sending message reply")
return
}
}
})
第五步:(可选)测试 /w Postman
本文来自作者投稿,版权归原作者所有。如需转载,请注明出处:https://www.nxrte.com/jishu/im/46716.html