Home  >  Article  >  Backend Development  >  How to create a WebSocket server using golang

How to create a WebSocket server using golang

WBOY
WBOYOriginal
2023-12-17 22:32:22947browse

How to create a WebSocket server using golang

How to create a WebSocket server using golang

WebSocket is a protocol that enables two-way communication between the client and the server. It allows us to transfer data between client and server through a persistent connection. In this article, I will introduce you how to create a simple WebSocket server using golang and provide specific code examples.

  1. Preparation
    Before you start, you need to make sure you have installed golang correctly. You can download the installation package from the official website and follow the instructions to install it.
  2. Import dependencies
    We need to import the two dependency packages net/http and github.com/gorilla/websocket. net/http is used to create an HTTP server, gorilla/websocket is used to handle WebSocket connections.
import (
    "net/http"
    "github.com/gorilla/websocket"
)
  1. Create WebSocket server
    We use the http.HandleFunc() function to handle WebSocket connection requests, and use websocket.Upgrade()Function upgrades the HTTP protocol to the WebSocket protocol.
func wsHandler(w http.ResponseWriter, r *http.Request) {
    upgrader := websocket.Upgrader{
        CheckOrigin: func(r *http.Request) bool { return true },
    }

    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println("Upgrade error:", err)
        return
    }

    // 在这里处理WebSocket连接
}

In the wsHandler() function, we created an Upgrader object and set the CheckOrigin attribute to an anonymous Function, returns true to accept all cross-domain requests.

Next, we use the Upgrade() function to upgrade the HTTP protocol to the WebSocket protocol. If the upgrade fails, an error message will be printed and returned. If the upgrade is successful, we can use the conn object to handle the WebSocket connection.

  1. Processing WebSocket connections
    After the WebSocket connection is established, we can use the conn object to perform read and write operations. Here is a simple processing example:
for {
    messageType, message, err := conn.ReadMessage()
    if err != nil {
        log.Println("Read error:", err)
        break
    }

    log.Println("received message:", string(message))

    err = conn.WriteMessage(messageType, message)
    if err != nil {
        log.Println("Write error:", err)
        break
    }
}

In the above example, we use the ReadMessage() function to read the message sent by the client, and WriteMessage ()Function returns the message to the client. If an error occurs during reading or writing, we print the error message and break out of the loop.

  1. Start the WebSocket server
    Finally, we use the http.HandleFunc() function to register the wsHandler() function as a handler for handling WebSocket connections , and use the http.ListenAndServe() function to start the WebSocket server on the specified port.
func main() {
    http.HandleFunc("/ws", wsHandler)
    log.Println("WebSocket server started.")

    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe error:", err)
    }
}

In the above example, we registered the wsHandler() function as the handler for the "/ws" path. You can customize the path as needed.

  1. Client Test
    Now that we have completed the creation of the WebSocket server, we can communicate with it using any client that supports the WebSocket protocol. You can test this using your browser's developer tools, or use some WebSocket testing tools.

Summary
This article introduces how to use golang to create a simple WebSocket server and provides specific code examples. It is very simple to create a WebSocket server using golang, and it can easily achieve two-way communication. I hope this article will help you understand and use WebSocket.

The above is the detailed content of How to create a WebSocket server using golang. 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