Golang implementation of Simple TCP server 02--Implementation of ECHO Server/client

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

Echo Server/client implementation with Golang

In this section, we start by implementing a simple Echo Server/client to understand the specifics of Golang's implementation of TCP long connection servers.

First of all, let's first make a list of the implementation ideas and steps of the service side * *:
1. Create a Socket object that specifies its IP and port.
2. Start listening on the port specified by the socket.
3. If there is a new client connection request, establish a goroutine, read the client message in Goroutine, and forward it back until the client disconnects
4. The main process continues to listen on the port.

We can create a file named Server.go in the home folder of the lab environment where the server-side program code is written
The server-side program list is as follows:

Server.go

package mainimport (    "bufio"    "fmt"    "net"    "time")func main() {    var tcpAddr *net.TCPAddr    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())       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(string(message))       msg := time.Now().String() + "\n"       b := []byte(msg)       conn.Write(b)    }}

Next, we open the terminal and compile the service-side program:

Go Build Server.go

If the compilation succeeds, the successful server program will be seen in the home directory.

Next, is the * * Client's code implementation steps * *:
1. Create a socket object with IP and port specified on the IP and port of the server we implemented above.
2. Connect to the server using the created socket object.
3. After successful connection, open a goroutine, within this goroutine, periodically send a message to the server and accept the return message of the server until the error occurs or disconnects.

The list of procedures is as follows:

Client.go

package mainimport (    "bufio"    "fmt"    "net"    "time")var quitSemaphore chan boolfunc 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)    b := []byte("time\n")    conn.Write(b)    <-quitSemaphore}func onMessageRecived(conn *net.TCPConn) {    reader := bufio.NewReader(conn)    for {       msg, err := reader.ReadString('\n')       fmt.Println(msg)       if err != nil {         quitSemaphore <- true         break       }       time.Sleep(time.Second)       b := []byte(msg)       conn.Write(b)    }}

To compile the client:

Go Build Client.go

Finally, open two terminals, running server and client separately

You can see output similar to the following:

connected!
2015-03-19 23:42:08.4875559 +0800 CST

2015-03-19 23:42:09.4896132 +0800 CST

2015-03-19 23:42:10.4906704 +0800 CST

2015-03-19 23:42:11.4917277 +0800 CST

2015-03-19 23:42:12.4927849 +0800 CST

2015-03-19 23:42:13.4938422 +0800 CST

2015-03-19 23:42:14.4948995 +0800 CST

2015-03-19 23:42:15.4959567 +0800 CST

2015-03-19 23:42:16.497014 +0800 CST

2015-03-19 23:42:17.4980712 +0800 CST

2015-03-19 23:42:18.4991285 +0800 CST

2015-03-19 23:42:19.5001857 +0800 CST

In this way, a simple echo server/client implements the

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.