Home > Article > Backend Development > How to create a WebSocket server using golang
How to create a WebSocket server using golang
WebSocket is a protocol that enables two-way communication between the client and the server. It allows us to transfer data between client and server through a persistent connection. In this article, I will introduce you how to create a simple WebSocket server using golang and provide specific code examples.
net/http
and github.com/gorilla/websocket
. net/http
is used to create an HTTP server, gorilla/websocket
is used to handle WebSocket connections. import ( "net/http" "github.com/gorilla/websocket" )
http.HandleFunc()
function to handle WebSocket connection requests, and use websocket.Upgrade()
Function upgrades the HTTP protocol to the WebSocket protocol. func wsHandler(w http.ResponseWriter, r *http.Request) { upgrader := websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true }, } conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println("Upgrade error:", err) return } // 在这里处理WebSocket连接 }
In the wsHandler()
function, we created an Upgrader
object and set the CheckOrigin
attribute to an anonymous Function, returns true to accept all cross-domain requests.
Next, we use the Upgrade()
function to upgrade the HTTP protocol to the WebSocket protocol. If the upgrade fails, an error message will be printed and returned. If the upgrade is successful, we can use the conn
object to handle the WebSocket connection.
conn
object to perform read and write operations. Here is a simple processing example: for { messageType, message, err := conn.ReadMessage() if err != nil { log.Println("Read error:", err) break } log.Println("received message:", string(message)) err = conn.WriteMessage(messageType, message) if err != nil { log.Println("Write error:", err) break } }
In the above example, we use the ReadMessage()
function to read the message sent by the client, and WriteMessage ()
Function returns the message to the client. If an error occurs during reading or writing, we print the error message and break out of the loop.
http.HandleFunc()
function to register the wsHandler()
function as a handler for handling WebSocket connections , and use the http.ListenAndServe()
function to start the WebSocket server on the specified port. func main() { http.HandleFunc("/ws", wsHandler) log.Println("WebSocket server started.") err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal("ListenAndServe error:", err) } }
In the above example, we registered the wsHandler()
function as the handler for the "/ws" path. You can customize the path as needed.
Summary
This article introduces how to use golang to create a simple WebSocket server and provides specific code examples. It is very simple to create a WebSocket server using golang, and it can easily achieve two-way communication. I hope this article will help you understand and use WebSocket.
The above is the detailed content of How to create a WebSocket server using golang. For more information, please follow other related articles on the PHP Chinese website!