Home  >  Article  >  Backend Development  >  How to use Go language with WebSocket

How to use Go language with WebSocket

PHPz
PHPzOriginal
2023-06-03 22:31:36924browse

In today's world, network communication has become an indispensable part. WebSocket technology is a protocol that establishes two-way communication between a web browser and a server. This communication method is efficient and real-time, so it is increasingly popular in modern web applications. At the same time, the Go language is also highly regarded for its efficiency and ease of writing concurrent programs. Therefore, how to use Go language in WebSocket has become a hot topic.

This article will introduce how to use Go language to implement two-way communication based on WebSocket. We will start with the basic concepts of WebSocket, then introduce how to implement a simple WebSocket server using the Go language, and finally show how to write a simple client program to test WebSocket communication.

1. The basic concept of WebSocket

WebSocket is a protocol based on the TCP protocol, which allows real-time two-way communication between the browser and the server. This is different from the HTTP protocol, which is a one-way communication protocol. The browser sends a request to the server, and the server sends a response to the browser.

The WebSocket protocol is a persistent protocol that allows the connection between the client and the server to remain open without having to constantly establish and close the connection. This makes the WebSocket protocol suitable for real-time applications such as online games, instant messaging applications, and stock market quotes.

The WebSocket protocol is a protocol established on an HTTP connection. When establishing a connection, the client sends an HTTP request to the server, and the request header contains the "Upgrade" field and the "Connection" field. These fields tell the server that the client is requesting an upgrade to the WebSocket protocol and that the server remains connected.

If the server accepts the WebSocket connection request, the "Upgrade" field and the "Connection" field will be included in the HTTP response header, and a standard WebSocket handshake response will be provided. After the handshake is complete, the WebSocket connection is considered established and the client and server can communicate directly in both directions.

The WebSocket protocol also allows the use of subprotocols, which means that the client and server can negotiate to use a specific protocol. If a subprotocol is used, the client and server can send data to each other, and the data will be interpreted as messages for that subprotocol.

2. Use Go language to implement WebSocket server

In order to use Go language to implement WebSocket server, we will use "net/http" and "golang.org/x" in the standard library of Go language /net/websocket" package.

We need to write an HTTP processing function to handle WebSocket connection requests, and then register the processing function with the websocker.Handler function. The HTTP handler function will be responsible for upgrading the HTTP connection to the WebSocket connection and handling the message exchange between the client and server once the connection is established.

The following is a sample code for a simple WebSocket server implemented in Go language:

package main

import (
    "log"
    "net/http"
    "golang.org/x/net/websocket"
)

func wsHandler(ws *websocket.Conn) {
    var message string
    for {
        err := websocket.Message.Receive(ws, &message)
        if err != nil {
            log.Println("Error receiving message:", err)
            break
        }
        log.Println("Received message:", message)
    }
}

func main() {
    http.Handle("/ws", websocket.Handler(wsHandler))
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

In this example, we define a function named "wsHandler" which will connect to Called after creation. This function accepts a parameter of type websocket.Conn, which represents the WebSocket connection.

In the wsHandler function, we use the websocket.Message.Receive function to receive the message from the WebSocket connection and simply print the message to the console.

In the main function, we use the http.Handle function to register the WebSocket handler named "/ws" as an HTTP handler. Then, we use the http.ListenAndServe function to run the server by specifying the server address and port.

3. Write a simple client program to test WebSocket communication

In order to test the WebSocket connection, we can write a simple WebSocket client program. In this program, we will use the "net/http" and "golang.org/x/net/websocket" packages from the standard library of the Go language.

The following is a sample code for a simple WebSocket client implemented in Go language:

package main

import (
    "fmt"
    "log"
    "golang.org/x/net/websocket"
)

func main() {
    origin := "http://localhost/"
    url := "ws://localhost:8080/ws"
    ws, err := websocket.Dial(url, "", origin)
    if err != nil {
        log.Fatal("Error dialing:", err)
    }
    defer ws.Close()

    message := []byte("Hello, world!")
    _, err = ws.Write(message)
    if err != nil {
        log.Fatal("Error sending message:", err)
    }

    var response []byte
    _, err = ws.Read(response)
    if err != nil {
        log.Fatal("Error receiving response:", err)
    }

    fmt.Println(string(response))
}

In this example, we use the websocket.Dial function to establish a connection with the WebSocket server. We specified the URL and source address of the WebSocket server. We can then send a byte array message using the WebSocket connection's Write method. Next, we use the Read method of the WebSocket connection to read the message returned by the server and print the message on the console.

Finally, we can compile and run the program to ensure that the WebSocket connection is successfully established and communication between the client and server is achieved.

4. Conclusion

In this article, we introduced the basic concepts of WebSocket and showed how to use Go language to implement a simple WebSocket server and client program. WebSocket technology allows Web applications to achieve real-time two-way communication more efficiently, and the Go language's efficiency and ease of writing concurrent programs make it an excellent language choice for implementing WebSocket servers.

Although only basic knowledge and sample code are introduced in this article, readers can further develop more complex WebSocket applications based on these sample codes. I believe that with the adoption of more web applications and the development of WebSocket technology, the Go language will become the preferred development language for more and more WebSocket servers.

The above is the detailed content of How to use Go language with WebSocket. 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