Learn network programming functions in Go language and implement a WebSocket server chat room?

王林
Release: 2023-07-30 18:43:54
Original
878 people have browsed it

Learn network programming functions in Go language and implement WebSocket server chat rooms

Introduction
With the rapid development of the Internet, Web applications have become an indispensable part of people's lives. Achieving real-time communication is one of the important components of Web applications. WebSocket is a protocol that provides two-way communication and can establish a persistent connection between the browser and the server. This article will introduce how to use the network programming functions in the Go language and combine it with the WebSocket protocol to implement a simple chat room server.

Preparation
Before you start writing code, you need to install the Go language development environment and understand the basic syntax of Go. In addition, we also need to use an open source WebSocket library to simplify the processing of the WebSocket protocol. The library can be installed through the following command:

go get github.com/gorilla/websocket
Copy after login

Code implementation
First, we need to import the necessary packages:

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/websocket"
)
Copy after login

Next, define the upgrader for the WebSocket connection. The upgrader is a http.HandlerFunc, which upgrades the HTTP connection to a WebSocket connection:

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}
Copy after login

Then, define a structure to represent the chat room server:

type ChatRoom struct {
    clients   map[*websocket.Conn]bool
    broadcast chan []byte
}

func newChatRoom() *ChatRoom {
    return &ChatRoom{
        clients:   make(map[*websocket.Conn]bool),
        broadcast: make(chan []byte),
    }
}
Copy after login

Next, implement the chat room server Methods. The first is the handleWebSocket function, which is used to handle the upgrade of WebSocket connections and message processing:

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

    c.clients[conn] = true

    for {
        _, msg, err := conn.ReadMessage()
        if err != nil {
            log.Println(err)
            delete(c.clients, conn)
            break
        }

        c.broadcast <- msg
    }

    defer conn.Close()
}
Copy after login

Then, implement the broadcastMessage function, which is used to broadcast messages to all connected clients:

func (c *ChatRoom) broadcastMessage() {
    for {
        msg := <-c.broadcast

        for client := range c.clients {
            err := client.WriteMessage(websocket.TextMessage, msg)
            if err != nil {
                log.Println(err)
                client.Close()
                delete(c.clients, client)
            }
        }
    }
}
Copy after login

Finally , implement the main function, used to start the chat room server:

func main() {
    room := newChatRoom()

    go room.broadcastMessage()

    http.HandleFunc("/ws", room.handleWebSocket)

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

Run
Run the following command in the code directory to start the chat room server:

go run main.go
Copy after login

Then access http in the browser: //localhost:8080, open the browser's developer tools, switch the console to the WebSocket tab, use the following JavaScript code to connect to the server:

var socket = new WebSocket("ws://localhost:8080/ws");

socket.onopen = function(event) {
  console.log("Connected to the server");
};

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

socket.onclose = function(event) {
  console.log("Disconnected from the server");
};

socket.send("Hello, server!");
Copy after login

Now, you can do this between the browser and the server Real-time two-way communication.

Summary
By learning the network programming functions in Go language and combining with the WebSocket protocol, we implemented a simple chat room server. WebSocket can establish a persistent connection between the browser and the server to achieve real-time communication. With the help of Golang's network programming functions, we can easily handle WebSocket connections and message transmission. I hope this article can help you learn network programming and WebSocket in Go language.

The above is the detailed content of Learn network programming functions in Go language and implement a WebSocket server chat room?. 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