Golang Implementing Simple TCP Server 03--Text Broadcast chat server/client

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Implementing text Broadcast Chat server/client with Golang

In this section, we will step through the previous section to complete the ECHO Server/client into a text message chat room

changes to the service side

    1. The server needs to record all client information connected to the server in order to enable group broadcast of chat information, so we need to add a collection to hold all client connections:

      var connmap map[string]*net. Tcpconn

    2. Then, each time a new client connects to the server, the client connection line information needs to be added to the collection:

      Connmap[tcpconn.remoteaddr (). String ()] = Tcpconn

    3. When the server receives the client's chat information, it needs to broadcast to all clients, so we need to use the map above to save Tcpconn to traverse all the tcpconn for broadcast, using the following method:

      func boradcastMessage(message string) {    b := []byte(message)    for _, conn := range ConnMap {    conn.Write(b)    }}

Client code Churn

The client code churn is relatively simple, just add the user's own input chat information function, after the connection is successful and start the message received Gorountine, add the following code:

    for {       var msg string       fmt.Scanln(&msg)       if msg == "quit" {         break       }       b := []byte(msg + "\n")       conn.Write(b)    }

The full service-side code is as follows:

Server.go

The package Mainimport ("Bufio" "FMT" "NET")//is used to record all client connections to Var connmap map[string]*net. Tcpconnfunc Main () {var tcpaddr *net. Tcpaddr Connmap = Make (map[string]*net. Tcpconn) Tcpaddr, _ = net. RESOLVETCPADDR ("TCP", "127.0.0.1:9999") TcpListener, _: = Net.  LISTENTCP ("TCP", TCPADDR) defer tcplistener.close () for {tcpconn, err: = Tcplistener.accepttcp () If Err ! = Nil {continue} fmt. PRINTLN ("A Client connected:" + tcpconn.remoteaddr (). String ())//New connection Join Map connmap[tcpconn.remoteaddr (). String ()] = Tcpconn go tcppipe (tcpconn)}}func tcppipe (Conn *net. Tcpconn) {ipstr: = conn. Remoteaddr (). String () defer func () {fmt. Println ("Disconnected:" + IPSTR) Conn. Close ()} () Reader: = Bufio. Newreader (conn) for {message, err: = Reader. ReadString (' \ n ') if err! = nil {return} FMT. PRINTLN (Conn. Remoteaddr (). String () + ":" + string (message))//return message here changed to broadcast BOradcastmessage (Conn. Remoteaddr ().    String () + ":" + string (message))}}func boradcastmessage (message string) {b: = []byte (message)//traverse all clients and send messages For _, Conn: = Range CONNMAP {Conn. Write (b)}}

The client complete code is as follows:

Client.go

package mainimport (    "bufio"    "fmt"    "net")func main() {    var tcpAddr *net.TCPAddr    tcpAddr, _ = net.ResolveTCPAddr("tcp", "127.0.0.1:9999")    conn, _ := net.DialTCP("tcp", nil, tcpAddr)    defer conn.Close()    fmt.Println("connected!")    go onMessageRecived(conn)    // 控制台聊天功能加入    for {       var msg string       fmt.Scanln(&msg)       if msg == "quit" {         break       }       b := []byte(msg + "\n")       conn.Write(b)    }}func onMessageRecived(conn *net.TCPConn) {    reader := bufio.NewReader(conn)    for {       msg, err := reader.ReadString('\n')       fmt.Println(msg)       if err != nil {         quitSemaphore <- true         break       }    }}

Finally, compile the server and client test results separately!

Go Build Server.go

Go Build Client.go

Start the server side first, and then open two new terminals, start the client, in one of the clients type chat information and enter, you will find another client received a chat the next day information just sent

Bob!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.