Learn network programming functions in Go language and implement real-time communication with WebSocket servers?

WBOY
Release: 2023-07-31 16:41:32
Original
1460 people have browsed it

Learn network programming functions in Go language and implement real-time communication with WebSocket servers

In today's Internet era, real-time communication is becoming more and more important in many applications. In order to achieve real-time communication, many developers will choose to use the WebSocket protocol because it provides a way to achieve two-way communication between the client and the server. In this article, we will learn the network programming functions in Go language and use it to implement a simple WebSocket server for real-time communication.

Before we start, we need to install the Go language development environment. I won’t go into details here. If you haven’t installed it yet, please refer to the Go language official website to install it.

First, we need to use the net/http package of the Go language to build a basic HTTP server, and then use the gorilla/websocket package to handle the WebSocket connection with the client.

  1. Import the required packages:
import (
    "log"
    "net/http"
    "github.com/gorilla/websocket"
)
Copy after login
  1. Define the WebSocket upgrader:
var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}
Copy after login
  1. Define the WebSocket handler function :
func wsHandler(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println(err)
        return
    }

    for {
        messageType, message, err := conn.ReadMessage()
        if err != nil {
            log.Println(err)
            return
        }

        log.Printf("Received message: %s
", message)

        if err := conn.WriteMessage(messageType, message); err != nil {
            log.Println(err)
            return
        }
    }
}
Copy after login
  1. Define the HTTP request handling function:
func helloHandler(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "index.html")
}
Copy after login
  1. Start the server:
func main() {
    http.HandleFunc("/ws", wsHandler)
    http.HandleFunc("/", helloHandler)
    log.Println("Server starting on localhost:8080")
    http.ListenAndServe(":8080", nil)
}
Copy after login

Now we are done Created a simple WebSocket server. We can open the index.html file in the browser and then use JavaScript code to communicate with the server.

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Example</title>
    <script>
        var socket = new WebSocket("ws://localhost:8080/ws");

        socket.onopen = function(event) {
            console.log("Connection opened.");
        };

        socket.onmessage = function(event) {
            console.log("Received message: " + event.data);
        };

        socket.onclose = function(event) {
            console.log("Connection closed.");
        };

        socket.onerror = function(event) {
            console.log("Error: " + event.data);
        };

        function sendMessage() {
            var message = document.getElementById("message").value;
            socket.send(message);
            console.log("Sent message: " + message);
        }
    </script>
</head>
<body>
    <input type="text" id="message" placeholder="Type a message">
    <button onclick="sendMessage()">Send</button>
</body>
</html>
Copy after login

The above code can be tested in the browser. The message can be sent to the server by entering the message in the input box and clicking the send button. The server will return the received message to the client as is and output it on the console. In this way, we have achieved a simple real-time communication.

By learning the network programming functions in the Go language and using the gorilla/websocket package to handle WebSocket connections, we can easily implement a WebSocket server for real-time communication. Not only that, the efficiency and concurrency of the Go language also make it an excellent language choice for handling real-time communications. I hope this article will be helpful for you to learn network programming in Go language and implement WebSocket server.

The above is the detailed content of Learn network programming functions in Go language and implement real-time communication with WebSocket servers?. For more information, please follow other related articles on the PHP Chinese website!

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!