Home Backend Development Golang Go language Websocket development practice: how to handle exceptions and close connections

Go language Websocket development practice: how to handle exceptions and close connections

Dec 14, 2023 pm 01:40 PM
go language websocket Exception handling

Go language Websocket development practice: how to handle exceptions and close connections

Go Language Websocket Development Practice: How to Handle Abnormal Closure of Connections

Introduction:
In Web development, two-way communication can be achieved using the Websocket protocol, which is usually used Real-time data transmission, chat applications and other scenarios. However, when using Websocket, it is easy to encounter unexpected connection interruptions, such as network fluctuations, abnormal client shutdown, etc. How to correctly handle abnormal connection closing in this case and ensure the stability and reliability of the application have become issues that need to be focused on during development. This article will combine sample code and take the Go language as an example to introduce how to handle exceptions and close connections.

1. Create a Websocket server:
First, we need to create a simple Websocket server. The following is a basic sample code:

package main

import (
    "fmt"
    "github.com/gorilla/websocket"
    "net/http"
)

// 定义Websocket读写的缓冲区大小
const bufferSize = 1024

// Websocket处理函数
func wsHandler(w http.ResponseWriter, r *http.Request) {
    // 升级HTTP连接为Websocket连接
    conn, err := websocket.Upgrade(w, r, nil, bufferSize, bufferSize)
    if err != nil {
        fmt.Println("Failed to upgrade the connection to websocket: ", err)
        return
    }

    for {
        // 读取客户端发送的消息
        messageType, message, err := conn.ReadMessage()
        if err != nil {
            fmt.Println("Failed to read message from client: ", err)
            break
        }

        // 处理接收到的消息
        handleMessage(conn, messageType, message)
    }

    // 关闭连接
    defer conn.Close()
}

// 处理接收到的消息
func handleMessage(conn *websocket.Conn, messageType int, message []byte) {
    // 处理消息的逻辑
    fmt.Println("Received message: ", string(message))
}
Copy after login

2. Handle abnormal closing of the connection:
When the client closes abnormally, the server needs to be able to correctly detect that the connection has been closed and handle it accordingly. The following is a sample code on how to handle abnormally closed connections:

// Websocket处理函数
func wsHandler(w http.ResponseWriter, r *http.Request) {
    // 升级HTTP连接为Websocket连接
    conn, err := websocket.Upgrade(w, r, nil, bufferSize, bufferSize)
    if err != nil {
        fmt.Println("Failed to upgrade the connection to websocket: ", err)
        return
    }

    // 异常关闭连接处理协程
    go handleCloseConnection(conn)

    for {
        // 读取客户端发送的消息
        messageType, message, err := conn.ReadMessage()
        if err != nil {
            // 检测到连接异常关闭的错误
            if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
                fmt.Println("Connection closed unexpectedly: ", err)
                break
            }
            // 其他错误处理
            fmt.Println("Failed to read message from client: ", err)
            break
        }

        // 处理接收到的消息
        handleMessage(conn, messageType, message)
    }

    // 关闭连接
    conn.Close()
}

// 异常关闭连接处理协程
func handleCloseConnection(conn *websocket.Conn) {
    // 读取关闭消息,表示客户端主动关闭连接
    _, _, err := conn.ReadMessage()
    if err != nil {
        fmt.Println("Failed to read close message from client: ", err)
    }

    // 处理连接关闭后的逻辑
    fmt.Println("Connection closed by client")
}
Copy after login

In the above sample code, we determine whether the connection is abnormally closed by calling the IsUnexpectedCloseError function. If the connection is abnormally closed, the corresponding error message will be recorded, the loop will be jumped out, and the connection will be closed. In addition, we also added a coroutine function named handleCloseConnection to handle the logic after the connection is closed.

Conclusion:
When developing Websocket applications, handling exceptions and closing connections is a very important step. By using the IsUnexpectedCloseError function and coroutine processing, we can detect and handle abnormal connection closures, avoiding application crashes due to connection exceptions. In actual applications, corresponding expansion can be carried out according to specific needs, such as recording logs, sending notifications, etc., to improve the reliability and maintainability of the application.

References:

  • [Gorilla WebSocket](https://github.com/gorilla/websocket)
  • [Go Standard Library Documentation](https: //golang.org/pkg/net/http/)
  • [WebSocket Protocol Development Guide](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket_API/Writing_WebSocket_servers)

The above is the detailed content of Go language Websocket development practice: how to handle exceptions and close connections. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between performance testing and unit testing in Go language The difference between performance testing and unit testing in Go language May 08, 2024 pm 03:09 PM

Performance tests evaluate an application's performance under different loads, while unit tests verify the correctness of a single unit of code. Performance testing focuses on measuring response time and throughput, while unit testing focuses on function output and code coverage. Performance tests simulate real-world environments with high load and concurrency, while unit tests run under low load and serial conditions. The goal of performance testing is to identify performance bottlenecks and optimize the application, while the goal of unit testing is to ensure code correctness and robustness.

How does C++ exception handling support custom error handling routines? How does C++ exception handling support custom error handling routines? Jun 05, 2024 pm 12:13 PM

C++ exception handling allows the creation of custom error handling routines to handle runtime errors by throwing exceptions and catching them using try-catch blocks. 1. Create a custom exception class derived from the exception class and override the what() method; 2. Use the throw keyword to throw an exception; 3. Use the try-catch block to catch exceptions and specify the exception types that can be handled.

Golang technology libraries and tools used in machine learning Golang technology libraries and tools used in machine learning May 08, 2024 pm 09:42 PM

Libraries and tools for machine learning in the Go language include: TensorFlow: a popular machine learning library that provides tools for building, training, and deploying models. GoLearn: A series of classification, regression and clustering algorithms. Gonum: A scientific computing library that provides matrix operations and linear algebra functions.

Exception handling in C++ technology: How to handle exceptions correctly in a multi-threaded environment? Exception handling in C++ technology: How to handle exceptions correctly in a multi-threaded environment? May 09, 2024 pm 12:36 PM

In multithreaded C++, exception handling follows the following principles: timeliness, thread safety, and clarity. In practice, you can ensure thread safety of exception handling code by using mutex or atomic variables. Additionally, consider reentrancy, performance, and testing of your exception handling code to ensure it runs safely and efficiently in a multi-threaded environment.

The role of Golang technology in mobile IoT development The role of Golang technology in mobile IoT development May 09, 2024 pm 03:51 PM

With its high concurrency, efficiency and cross-platform nature, Go language has become an ideal choice for mobile Internet of Things (IoT) application development. Go's concurrency model achieves a high degree of concurrency through goroutines (lightweight coroutines), which is suitable for handling a large number of IoT devices connected at the same time. Go's low resource consumption helps run applications efficiently on mobile devices with limited computing and storage. Additionally, Go’s cross-platform support enables IoT applications to be easily deployed on a variety of mobile devices. The practical case demonstrates using Go to build a BLE temperature sensor application, communicating with the sensor through BLE and processing incoming data to read and display temperature readings.

How to handle exceptions in C++ Lambda expressions? How to handle exceptions in C++ Lambda expressions? Jun 03, 2024 pm 03:01 PM

Exception handling in C++ Lambda expressions does not have its own scope, and exceptions are not caught by default. To catch exceptions, you can use Lambda expression catching syntax, which allows a Lambda expression to capture a variable within its definition scope, allowing exception handling in a try-catch block.

What are the advantages of golang framework? What are the advantages of golang framework? Jun 06, 2024 am 10:26 AM

Advantages of the Golang Framework Golang is a high-performance, concurrent programming language that is particularly suitable for microservices and distributed systems. The Golang framework makes developing these applications easier by providing a set of ready-made components and tools. Here are some of the key advantages of the Golang framework: 1. High performance and concurrency: Golang itself is known for its high performance and concurrency. It uses goroutines, a lightweight threading mechanism that allows concurrent execution of code, thereby improving application throughput and responsiveness. 2. Modularity and reusability: Golang framework encourages modularity and reusable code. By breaking the application into independent modules, you can easily maintain and update the code

PHP exception handling: understand system behavior through exception tracking PHP exception handling: understand system behavior through exception tracking Jun 05, 2024 pm 07:57 PM

PHP exception handling: Understanding system behavior through exception tracking Exceptions are the mechanism used by PHP to handle errors, and exceptions are handled by exception handlers. The exception class Exception represents general exceptions, while the Throwable class represents all exceptions. Use the throw keyword to throw exceptions and use try...catch statements to define exception handlers. In practical cases, exception handling is used to capture and handle DivisionByZeroError that may be thrown by the calculate() function to ensure that the application can fail gracefully when an error occurs.

See all articles