目錄的
>>項目設定
本教學建構了基本的WebSocket伺服器與客戶端:
>客戶與伺服器互動的客戶
安裝大猩猩Websocket軟體包:
<code>websocket-server/ ├── main.go # Application entry point ├── handlers/ # WebSocket handler functions │ └── websocket.go # Handles WebSocket connections and messages ├── static/ # Client-side HTML/JS files │ └── index.html # Simple client interface └── go.mod # Go module file</code>
>步驟1:
<code class="language-bash">go get -u github.com/gorilla/websocket</code>
main.go
這設定了HTTP伺服器,提供靜態文件,並在步驟2:websocket處理程序(main.go
)
<code class="language-go">package main import ( "fmt" "log" "net/http" "websocket-server/handlers" ) func main() { http.HandleFunc("/ws", handlers.HandleWebSocket) http.Handle("/", http.FileServer(http.Dir("./static"))) port := ":8080" fmt.Printf("Server running on http://localhost%s\n", port) log.Fatal(http.ListenAndServe(port, nil)) }</code>
>目錄中,建立/ws
:
websocket.go
這個處理程序升級HTTP連接,讀取訊息並迴聲。
handlers
訊息處理websocket.go
<code class="language-go">package handlers import ( "fmt" "net/http" "github.com/gorilla/websocket" ) var upgrader = websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true }, } func HandleWebSocket(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { fmt.Println("Upgrade failed:", err) return } defer conn.Close() fmt.Println("Client connected") for { _, msg, err := conn.ReadMessage() if err != nil { fmt.Println("Read failed:", err) break } fmt.Printf("Received: %s\n", msg) if err := conn.WriteMessage(websocket.TextMessage, msg); err != nil { fmt.Println("Write failed:", err) break } } }</code>
>
)HandleWebSocket
index.html
。 然後,在瀏覽器中開啟index.html
(隨附適當的客戶端JavaScript)。
本教學使用大猩猩示範了基本的GO Websocket伺服器。 WebSocket是即時應用程式的理想選擇。 根據需要通過身份驗證,廣播和資料儲存擴展此基礎。
>[在此插入github儲存庫連結]
以上是與大猩猩一起創建WebSocket服務器的詳細內容。更多資訊請關注PHP中文網其他相關文章!