With the development of the Internet, the use of Web applications has become more and more common, making the WebSocket protocol increasingly a popular protocol. On the other hand, the rapid growth of Golang has made it a popular language of choice for WebSockets. In this article, we will introduce how to use Golang for WebSocket programming.
What is WebSocket?
The WebSocket protocol is a two-way, real-time communication protocol that enables web applications to interact with servers. Unlike the HTTP protocol, the WebSocket protocol allows the server and client to send and receive messages at any time, enabling real-time communication.
Generally speaking, Web applications use the WebSocket protocol for real-time data exchange, such as online chat, real-time hotspots, multiplayer games, etc. Using WebSockets, programmers can achieve efficient real-time communication with a small amount of code.
Implementing WebSocket using Golang
Golang is the perfect language because it provides built-in RPC and Socket support. Using Golang's net/http package, we can easily create a WebSocket server.
import (
"log" "net/http" "github.com/gorilla/websocket"
)
In this step, we will create the server to handle WebSocket requests. For each WebSocket connection we need to create a handler to read and write messages.
func websocketHandler(w http.ResponseWriter, r *http.Request) {
ws, err := websocket.Upgrade(w, r, nil, 1024, 1024) if err != nil { log.Println(err) return } defer ws.Close() for { messageType, p, err := ws.ReadMessage() if err != nil { log.Println(err) break } log.Println(string(p)) err = ws.WriteMessage(messageType, []byte("Server: got your message")) if err != nil { log.Println(err) break } }
}
In this handler, we first upgrade the HTTP request to a WebSocket connection . We then loop for each connection reading the message sent from the client and output the message in the console. Finally, we write the message back to the client again to let the client know that we successfully received the message.
Next, we need to add Web Socket routing to our server. In this example, we will use the Gorilla WebSocket library. You can use standard library alternatives - for example:
http.HandleFunc("/echo", websocketHandler)
Requires manual import of the Gorilla WebSocket library:
var upgrader = websocket .Upgrader{
ReadBufferSize: 1024, WriteBufferSize: 1024,
}
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
// Upgrade the HTTP server connection to a web socket connection ws, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println(err) return } // ... WebSocket connection logic ...
})
Once your routes are set up, you can initiate a WebSocket connection on the server via:
func main() {
log.Println("Starting server on :8080") http.HandleFunc("/ws", websocketHandler) err := http.ListenAndServe(":8080", nil) log.Fatal(err)
}
Then you can start the server and connect the client. Open a new terminal window and use the curl command to send text to the server via WebSocket:
curl -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: localhost:8080" - H "Origin: http://localhost:8080" http://localhost:8080/ws -v
Also, you can use online tools such as the Chrome plug-in Simple WebSocket Client for testing.
Summary
WebSocket is an excellent choice for real-time communication. With the built-in RPC and Socket support provided by Golang, we are able to easily create a WebSocket server. In this article, we describe the basic steps on how to create a WebSocket using Golang. Now that you have mastered the basics of WebSockets in Golang, you can start building your own real-time applications.
The above is the detailed content of How to use websocket in golang. For more information, please follow other related articles on the PHP Chinese website!