go language to realize chat room

Keywords: Go

go language to realize chat room

Chat room is divided into server and client. The first part is the server code, the second part is the client code.

I. server code

//chatroom server
package main

import (
    "fmt"
    "net"
)

//Define the function checkError for error handling
func checkError(err error)  {
    if err != nil {
        panic(err)
    }
}

//Define a function that is specifically responsible for receiving information
func processInfo(conn net.Conn)  {
    buf := make([]byte, 1024)
    defer conn.Close()

    for {
        //Read data
        numOfBytes, err := conn.Read(buf)
        if err != nil {
            break
        }

        //If the number of bytes received is not 0, a message is sent
        if numOfBytes != 0 {
            fmt.Printf("Has received message: %s", string(buf))
        }

    }
}

func main()  {
    //Turn on monitoring
    listen_socket, err := net.Listen("tcp","127.0.0.1:8888")
    checkError(err)
    defer listen_socket.Close()

    fmt.Println("chat room Server is waiting... ")

    //Receiving connection
    for {
        conn, err := listen_socket.Accept()
        checkError(err)

        //If there is a client connection, open a process
        go processInfo(conn)

    }
}

Executing go build server.go or go run server.go will output: chat room Server is waiting... And wait for the client to connect

II. Client code

// chat room client
package main

import (
    "fmt"
    "net"
)

func checkError(err error)  {
    if err != nil {
        panic(err)
    }
}

func main()  {
    //Information about connecting to the server
    conn, err := net.Dial("tcp","127.0.0.1:8888")
    checkError(err)
    defer conn.Close()

    //Send information to the server
    conn.Write([]byte("Now connection.success!"))

    fmt.Println("Has sent the message!")
}

Executing go run client.go or go build client.go will output: Has sent the message!
At this time, the client has sent a message to the server: Now connection.success

Let's check the output terminal of the server. At this time, the server outputs the following content, which means that the client and the server communicate successfully.
chat room Server is waiting...
Has received message: Now connection.success!

Posted by printf on Sat, 07 Dec 2019 12:30:54 -0800