Home >Backend Development >Golang >golang WebSocket Tutorial: How to achieve real-time communication
Golang WebSocket Tutorial: How to achieve real-time communication
First, let us introduce what WebSocket is. WebSocket is a protocol for full-duplex communication between a web browser and a server. Unlike the HTTP protocol, WebSocket allows the server to push data to the client and can implement real-time communication, event-driven and other functions.
In this tutorial, we will use Golang to implement a simple WebSocket server. We'll demonstrate how to establish a WebSocket connection, send and receive messages, and illustrate with concrete code examples.
First, we need to import Golang's WebSocket package:
import ( "log" "net/http" "github.com/gorilla/websocket" )
Then, we need to define a WebSocket upgrader (upgrader) to upgrade the HTTP protocol to the WebSocket protocol:
var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool { return true }, }
Next, we need to define a function that handles WebSocket connections. This function will be registered as an HTTP handler and will be called every time there is a WebSocket connection request:
func handleWebSocket(w http.ResponseWriter, r *http.Request) { // 将HTTP连接升级为WebSocket连接 conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println(err) return } // 在新的goroutine中处理WebSocket连接 go handleWebSocketConnection(conn) }
In the function that handles the WebSocket connection, we need to define a loop to handle receiving and sending messages:
func handleWebSocketConnection(conn *websocket.Conn) { for { // 读取客户端发送的消息 _, msg, err := conn.ReadMessage() if err != nil { log.Println(err) return } // 打印接收到的消息 log.Println("Received message:", string(msg)) // 发送消息给客户端 err = conn.WriteMessage(websocket.TextMessage, []byte("Hello, client!")) if err != nil { log.Println(err) return } } }
Now, we only need to register the above function as an HTTP processor and start an HTTP server:
func main() { // 注册WebSocket处理器 http.HandleFunc("/ws", handleWebSocket) // 启动HTTP服务器 log.Println("WebSocket server started on localhost:8080") err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal(err) } }
At this point, we have completed a simple WebSocket server. When a client connects to the server through WebSocket, the server will receive the message sent by the client and reply with a fixed message.
To test the server, we can use a browser plug-in, such as "Simple WebSocket Client", enter the server address ws://localhost:8080/ws and connect. Enter the message in the plug-in's message box and send it. We will be able to see the received message in the terminal and reply a message to the client at the same time.
The above is our basic tutorial on using Golang to implement WebSocket. WebSocket has great potential in real-time communication, event-driven, etc., and can be used in chat applications, real-time data visualization and other scenarios. Through this tutorial, I hope it can provide some help for you to understand and use WebSocket.
The above is the detailed content of golang WebSocket Tutorial: How to achieve real-time communication. For more information, please follow other related articles on the PHP Chinese website!