php小編魚仔為您介紹如何註冊新的websocket連接gooptic。 GoOptic是一個開源的Go語言websocket庫,用於建立高效能、即時通訊的應用程式。要註冊新的websocket連接,首先需要在Go程式中匯入GoOptic庫。然後,可以使用GoOptic提供的函數來建立websocket伺服器,並指定要監聽的位址和連接埠。接下來,可以使用GoOptic提供的HandleFunc函數來處理websocket連接的各種事件,例如接收訊息、傳送訊息等。最後,呼叫GoOptic提供的Serve函數來啟動websocket伺服器,使其可以接受新的連線。透過這些步驟,您就可以成功註冊新的websocket連接gooptic。
我正在嘗試設定一個簡單的 websocket 伺服器,該伺服器應該以未知的時間間隔為客戶端提供一些內容。
我的程式碼目前如下所示:
router.go
#func setuproutes(app *fiber.app) error { app.get("/whop/validate", handler.handlewhopvalidate) /*other non-websocket routes*/ /*...*/ app.get("/ws/monitor", websocket.new(wshandler.handlewsmonitor)) app.use(func(c *fiber.ctx) error { c.sendstatus(404) return c.next() }) return nil }
handler.go
#package handlers import ( "fmt" "log" "github.com/gofiber/websocket/v2" ) var register = make(chan *websocket.conn) var unregister = make(chan *websocket.conn) func handlewsmonitor(c *websocket.conn) { go socketlistener() defer func() { unregister <- c //may need to check whether connection is already closed before re-closing? c.close() }() //sends conn into channel register <- c for { messagetype, message, err := c.readmessage() if err != nil { if websocket.isunexpectedcloseerror(err, websocket.closegoingaway, websocket.closeabnormalclosure) { log.println("read error:", err) } return } if messagetype == websocket.textmessage { log.println("got textmessage:", string(message)) } else { log.println("received message of type:", messagetype) } } } func socketlistener() { for { select { case c := <-register: messagetype, message, err := c.readmessage() if err != nil { log.println(err) unregister <- c return } fmt.printf("got message of type: %d\nmessage:%s\n", messagetype, string(message)) fmt.printf("connection params: %s\n", c.params("id")) //append to list of co case c := <-unregister: //remove conection from list of clients c.close() fmt.printf("closed connection\n") } } }
我遇到的問題是,當我連接到 websocket 時,我的註冊選擇案例未命中(我想使用之前提供給客戶端的 uuid 將客戶端連接註冊到地圖) .
client.go
#package main import ( "flag" "log" "net/url" "github.com/fasthttp/websocket" ) type Client struct { C *websocket.Conn } func main() { addr := flag.String("addr", "localhost:8080", "http service address") u := url.URL{ Scheme: "ws", Host: *addr, Path: "/ws/monitor", RawQuery: "id=12", } wsClient := &Client{} log.Printf("connecting to %s\n", u.String()) // Connect to the WebSocket server conn, resp, err := websocket.DefaultDialer.Dial(u.String(), nil) if err != nil { log.Fatal("Dial:", err) } wsClient.C = conn if resp != nil { log.Println("Got response:", resp) } defer wsClient.closeConn() } func (client *Client) closeConn() { err := client.C.WriteMessage( websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), ) if err != nil { log.Println("Write close:", err) return } client.C.Close() log.Println("Connection closed") }
handler.go 中是否缺少某些內容,或者我在使用客戶端連接到伺服器時是否應該採取不同的方法?
根據我的測試,暫存器的選擇案例確實命中(我使用的程式碼附在這個答案的底部)。
但是我在程式碼中發現了其他問題:
unregister
chan 是無緩衝的,socketlistener
中的 unregister <- c
將被阻塞。當程式碼到達 unregister <- c
時,它和 case c := <-unregister
之間出現死鎖。 socketlistener
goroutine。如果是這種情況,應將其移至 handlewsmonitor
之外。 handlewsmonitor
和 socketlistener
都從連線中讀取。 socketlistener
的職責是什麼?看來它不應該從連接中讀取。 再想想,好像可以直接在handlewsmonitor
中的地圖上新增連接和刪除連線。 socketlistener
可以完全刪除。簡單性應該是設計的關鍵目標。請參閱kiss 原則。
package main import ( "log" "github.com/gofiber/fiber/v2" "github.com/gofiber/websocket/v2" ) var ( register = make(chan *websocket.Conn) unregister = make(chan *websocket.Conn) ) func main() { // Make it easy to find out which line prints the log. log.SetFlags(log.Lshortfile) app := fiber.New() app.Get("/ws/monitor", websocket.New(HandleWsMonitor)) log.Fatal(app.Listen(":8080")) } func HandleWsMonitor(c *websocket.Conn) { // It seems the we only need one SocketListener goroutine for the whole server. // If this is the case, the next line should be moved outside of this func. go SocketListener() defer func() { unregister <- c c.Close() }() register <- c for { messageType, message, err := c.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { log.Println("read error:", err) } return } if messageType == websocket.TextMessage { log.Println("got textmessage:", string(message)) } else { log.Println("received message of type:", messageType) } } } func SocketListener() { for { select { case c := <-register: // This did appear in the log. log.Println("case c := <-register") messageType, message, err := c.ReadMessage() if err != nil { log.Println(err) // unregister is unbuffered, the sending will be blocked. unregister <- c // If we use only one SocketListener goroutine then it should // not return here. return } log.Printf("Got message of type: %d\nMessage:%s\n", messageType, string(message)) log.Printf("Connection Params: %s\n", c.Params("id")) case c := <-unregister: c.Close() log.Println("Closed connection") } } }
以上是如何註冊新的 websocket 連線 gooptic的詳細內容。更多資訊請關注PHP中文網其他相關文章!