Home > Backend Development > Golang > How to develop a simple chat application using Go language

How to develop a simple chat application using Go language

WBOY
Release: 2023-11-20 14:48:11
Original
1404 people have browsed it

How to develop a simple chat application using Go language

How to develop a simple chat application using Go language

With the rapid development of the Internet, chat applications have become an indispensable part of people's daily lives. As a fast, reliable and efficient programming language, Go language is increasingly favored by developers. This article will introduce how to develop a simple chat application using Go language.

1. Project Overview

We will use Go language to write a simple chat application. Users can send messages to other users through the application and receive messages sent by other users. Our chat application will communicate based on TCP protocol.

2. Project preparation

Before we start writing code, we need to install the Go language development environment. You can download the installation package from https://golang.org/dl/ and follow the prompts to install it.

After the installation is completed, we can verify whether the installation is successful through the command line. Open the command line window and enter the following command:

go version
Copy after login

If the version number of the Go language is displayed, the installation is successful.

3. Write code

Create a new directory, name it chatapp, and then create a file named main.go in the directory. We will write our chat application code in this file.

  1. Import dependencies

First, import the standard library of Go language and the dependencies required by the chat application:

package main

import (
    "bufio"
    "fmt"
    "log"
    "net"
    "os"
    "strings"
)
Copy after login
  1. Define global variables

Define some global variables outside the main function to store chat room-related information:

var (
    clients   = make(map[string]net.Conn)
    messages  = make(chan string)
    entering  = make(chan net.Conn)
    leaving   = make(chan net.Conn)
    allOnline = make(chan string)
)
Copy after login
  1. Define the function

Next, We define some functions to handle the logic of the chat room:

  • handleConnection: handle the connection logic, including the joining and leaving of new connections;
  • handleMessages: handle the message logic, broadcast the message to All online users;
  • listenForMessages: Listen for messages read from standard input;
  • listenForCommands: Listen for commands read from standard input.
func handleConnection(conn net.Conn) {
    entering <- conn

    scanner := bufio.NewScanner(conn)
    for scanner.Scan() {
        messages <- scanner.Text()
    }

    leaving <- conn
}

func handleMessages() {
    for {
        select {
        case msg := <-messages:
            for _, conn := range clients {
                fmt.Fprintln(conn, msg)
            }
        case conn := <-entering:
            clients[conn.RemoteAddr().String()] = conn
            allOnline <- fmt.Sprintf("User %s joined the chat.", conn.RemoteAddr().String())
        case conn := <-leaving:
            delete(clients, conn.RemoteAddr().String())
            allOnline <- fmt.Sprintf("User %s left the chat.", conn.RemoteAddr().String())
        }
    }
}

func listenForMessages() {
    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        messages <- scanner.Text()
    }
}

func listenForCommands() {
    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        command := scanner.Text()
        if strings.HasPrefix(command, "/list") {
            fmt.Println("Online users:")
            for client := range clients {
                fmt.Println(client)
            }
        } else if command == "/exit" {
            os.Exit(0)
        } else {
            fmt.Println("Unknown command:", command)
        }
    }
}
Copy after login
  1. main function

Finally, we write the main function and start the chat application in it:

func main() {
    log.Println("Starting chat server...")

    go handleMessages()

    listener, err := net.Listen("tcp", ":8080")
    if err != nil {
        log.Fatal(err)
    }

    defer listener.Close()

    go listenForMessages()
    go listenForCommands()

    for {
        conn, err := listener.Accept()
        if err != nil {
            log.Println(err)
            continue
        }
        go handleConnection(conn)
    }
}
Copy after login

4. Run the application

Save and close the main.go file. Open a command line window, enter the chatapp directory, and execute the following command to run the application:

go run main.go
Copy after login

5. Test the application

Open multiple command line windows and use the telnet command to connect to the chat application server:

telnet localhost 8080
Copy after login

The message can then be entered and sent to other online users. You can use the command "/list" to view the list of current online users, and the command "/exit" to exit the chat application.

6. Summary

Through the introduction of this article, we have learned how to use Go language to develop a simple chat application. In actual development, we can expand the chat application according to needs, such as adding user authentication, message storage and other functions. I hope this article is helpful to you, and I wish you develop more good applications in the world of Go language!

The above is the detailed content of How to develop a simple chat application using Go language. 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