How to build a WebSocket server using Go language

WBOY
Release: 2023-06-04 08:40:46
Original
1571 people have browsed it

WebSockets is an advanced network protocol that allows two-way communication between client and server over a single TCP connection. WebSockets support real-time data transmission, online games, chat rooms and other applications, so it is very popular among developers.

Go language is a high-performance, concise programming language suitable for building WebSockets servers. This article will introduce in detail how to build a WebSocket server using Go language.

  1. Understanding the WebSocket protocol

The WebSocket protocol uses the handshake and Upgrade header of the HTTP protocol to upgrade to a WebSocket connection. WebSocket connections always use carriage return and line feed characters as message terminators. WebSocket messages can be text or binary data.

  1. Install the Gorilla WebSocket library

The Gorilla WebSocket library is one of the most popular WebSocket libraries in the Go language. It provides implementations of WebSocket clients and servers. You can install the Gorilla WebSocket library using the following command:

go get github.com/gorilla/websocket
Copy after login
  1. Create WebSocket Server

Here is a simple WebSocket server example:

package main

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

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

func main() {
    http.HandleFunc("/echo", echoHandler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

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

    for {
        messageType, message, err := conn.ReadMessage()
        if err != nil {
            log.Println(err)
            break
        }
        log.Printf("Received message: %s
", message)
        err = conn.WriteMessage(messageType, message)
        if err != nil {
            log.Println(err)
            break
        }
    }
}
Copy after login

Above In the code, the echoHandler function handles all WebSocket connections. It uses the Upgrader provided by the Gorilla WebSocket library to upgrade HTTP requests to WebSocket connections. After the connection is upgraded, the server reads the message from the client using conn.ReadMessage() and echoes the message back to the client using conn.WriteMessage().

  1. Run the WebSocket server

Now, run the WebSocket server. In the terminal, go to the directory where the Go files are located and run the following command:

go run main.go
Copy after login

At this point, you should see output similar to the following:

2021/08/11 15:32:31 Listening on port 8080...
Copy after login

This means that your The server is listening on port 8080 for all incoming connections.

  1. Testing the WebSocket Server

Now that you have successfully created the WebSocket server, you can test it using the WebSocket client. It is recommended to use Chrome browser for testing because Chrome browser has built-in WebSocket client. Open the developer tools in Chrome, switch to the console tab and enter the following code:

var ws = new WebSocket("ws://localhost:8080/echo");
ws.onopen = function() {
    console.log("Connected");
    ws.send("Hello, World!");
};
ws.onmessage = function(event) {
    console.log("Received message: " + event.data);
};
ws.onclose = function() {
    console.log("Disconnected");
};
Copy after login

Chrome will establish a WebSocket connection to your server and send a "Hello, World!" message. Your server will echo the message and send it back to the client. You should see output similar to the following in the console:

Connected
Received message: Hello, World!
Disconnected
Copy after login
  1. Summary

This article explains how to build a WebSocket server using the Gorilla WebSocket library and the Go language. Now, you know how to use the WebSocket protocol to implement real-time communication capabilities. WebSocket allows you to use a single TCP connection to transfer data without establishing a new connection for each request. This improves performance and scalability, making it worthwhile to use in applications.

The above is the detailed content of How to build a WebSocket server using Go language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!