Home >Backend Development >Golang >Using Gin framework to implement Websocket communication function

Using Gin framework to implement Websocket communication function

王林
王林Original
2023-06-23 09:34:372921browse

With the continuous development of the Internet, there are more and more demands for Web applications. What followed was the need for real-time communication, and Websocket came into being. Gin is an efficient Web framework based on Golang. The Websocket communication function can be easily implemented through the Gin framework.

This article will introduce how to use the Gin framework to implement Websocket communication functions.

Install the Gin framework

Before you start using the Gin framework, you need to install the Gin framework first. It can be installed through the following command:

go get -u github.com/gin-gonic/gin

Create a Gin application

After installing the Gin framework, we can start creating a Gin application. Create a app.go file and implement it according to the following code:

package main

import (
    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()

    router.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })

    router.Run(":8080")
}

The above code creates a Gin application, the listening port is 8080, and accesses http:// in the browser localhost:8080/ping will return a JSON response.

Use Gin framework to implement Websocket

Next, we will use Gin framework to implement Websocket communication function. We will create a websocket.go file and follow the following steps to implement it:

Import dependencies

Before starting, you need to import the following dependencies:

import (
    "log"
    "net/http"

    "github.com/gorilla/websocket"
    "github.com/gin-gonic/gin"
)

Here we imported the Gin framework, Gorilla websocket library, and log and net/http in the Go standard library.

Define Gin routing

We define a Websocket route through the Gin framework:

router.GET("/ws", func(c *gin.Context) {
    wsHandler(c.Writer, c.Request)
})

Define Websocket processing function

We define a wsHandler Function, used to process Websocket connections:

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

func wsHandler(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println(err)
        return
    }

    defer conn.Close()

    for {
        // 读取消息
        _, msg, err := conn.ReadMessage()
        if err != nil {
            log.Println(err)
            return
        }

        // 处理消息
        log.Printf("收到消息: %s
", msg)

        // 回复消息
        err = conn.WriteMessage(websocket.TextMessage, []byte("已收到消息!"))
        if err != nil {
            log.Println(err)
            return
        }
    }
}

The above function upgrades the HTTP connection to a Websocket connection by calling the websocket.Upgrader method, and handles read and write operations in the Websocket connection. In the code, we first use the upgrader.Upgrade method to upgrade the HTTP connection to a Websocket connection. Then, in an infinite loop, use the conn.ReadMessage method to read the client's message data, print out the read message, and then use the conn.WriteMessage method to write a reply The message is returned to the client.

Websocket read and write operations are a blocking process, so they need to be performed in an infinite loop. The loop will exit when the client disconnects from the Websocket.

Test Websocket connection

After writing the above code, we can test the Websocket connection through the following steps:

  1. Start the Gin application: go run app. go
  2. Open the http://localhost:8080/ws page in the browser
  3. Open the browser's developer tools and execute the following in the console Code:
var websocket = new WebSocket("ws://localhost:8080/ws");

websocket.onopen = function(evt) {
    console.log("连接成功!");
    websocket.send("Hello WebSocket!");
};

websocket.onmessage = function(evt) {
    console.log("收到消息:" + evt.data);
};

websocket.onclose = function(evt) {
    console.log("连接已关闭!");
};

In the above code, we use the WebSocket API to establish a connection with Websocket and send a message. When the connection to Websocket is successfully established, the console will output "Connection successful!"; when a reply message from Websocket is received, the console will output "Message received: Message received!"; when the connection is closed, the control The station will output "Connection closed!".

Summary

Through the above steps, we successfully implemented the Websocket communication function using the Gin framework. The Gin framework provides a rich API that allows us to easily carry out web development. Websocket is an important mechanism for realizing real-time communication. Through the combination of Gin framework and Websocket, we can develop Web applications with real-time communication functions more conveniently and quickly.

The above is the detailed content of Using Gin framework to implement Websocket communication function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn