go to achieve tcp server

We will use the TCP protocol and coroutine paradigm write a simple client - server applications, a (web) server applications need to respond to many concurrent requests the client: Go Association will produce a process for each client to process the request. We need to use the function net network communications package. It contains a handle TCP / IP and UDP protocol, DNS and other methods.

Server-side code is a separate file:

Example. 1  server.go

Package Penalty for main 

Import (
     "fmt" 
    "NET" 
) 

FUNC main () { 
    fmt.Println ( "Starting at The Server ..." )
     // Create a listener 
    listener, ERR: = net.Listen ( "tcp", "localhost: 50000 " )
     IF ERR =! nil { 
        fmt.Println ( " Error listening " , err.Error ())
         return  // terminate the program 
    }
     // listens and accepts connections from clients 
    for { 
        Conn, ERR: = listener.Accept ()
         IF ERR! = nil { 
            FMT.Println("Error accepting", err.Error())
            return // 终止程序
        }
        go doServerStuff(conn)
    }
}

func doServerStuff(conn net.Conn) {
    for {
        buf := make([]byte, 512)
        len, err := conn.Read(buf)
        if err != nil {
            fmt.Println("Error reading", err.Error())
            return //终止程序
        }
        fmt.Printf("Received data: %v\n", string(buf[:len]))
    }
}

In  main() the creation of a  net.Listener type of variable  listener, he realized the basic functions of the server: to listen and receive requests from the client (ie the localhost IP address 127.0.0.1 is based on TCP port 50000). Listen() Function can return a  error type of error variables. For using an infinite loop  listener.Accept() waiting for client requests. Client's request will produce a  net.Conn type of connection variables. Then a separate coroutine execution use this connection  doServerStuff(), start using a 512-byte buffer  data to read the data transmitted to the client, and print them to the terminal server, len obtain the number of bytes of data sent by the client; when a customer when all of the data sent by the server are read completed, coroutine ended. This program creates a separate co-drive connection for each client. You must run the server code, and then run the client code.

Client code written in another file client.go in:

Example 2  client.go

Package main 

Import (
     "BUFIO" 
    "FMT" 
    "NET" 
    "OS" 
    "strings" 
) 

FUNC main () { 
    // Open the connection: 
    Conn, ERR: = net.Dial ( "TCP", "localhost: 50000" )
     IF ! ERR = nil {
         // because the target computer actively refused unable to create a connection 
        fmt.Println ( "Error Dialing" , err.Error ())
         return  // terminate the program 
    } 

    inputReader: = bufio.NewReader (os.Stdin) 
    fmt. println ( "First, the What IS your name?" ) 
    clientName, _:= inputReader.ReadString('\n')
     // fmt.Printf ( "CLIENTNAME% S", clientName) 
    trimmedClient: = strings.Trim (clientName, "\ r \ the n-") // with "\ r \ n", the Linux platform using the "Windows platform \ the n-"
     // send information to the server until the program exits: 
    for { 
        fmt.Println ( " to the send to the What at The server Type Q to quit "?. ) 
        the INPUT, _: = inputReader.ReadString ( '\ the n-' ) 
        trimmedInput: = strings.Trim (INPUT, "\ R & lt \ n-" )
         // fmt.Printf ( "INPUT: -% S - Canton", INPUT)
         // fmt.Printf ( "trimmedInput: -% S - Canton", trimmedInput ) 
        IF trimmedInput == "Q" {
            return
        }
        _, err = conn.Write([]byte(trimmedClient + " says: " + trimmedInput))
    }
}

The client by  net.Dial creating a connection between a server and.

It is through the endless loop  os.Stdin receives input from the keyboard until the input "Q". Note cropping  \r and  \n characters (only Windows platform required). Cropped input is  connection the  Write method of transmitting to the server.

Of course, the server must be started well, if the server does not start listening, the client is unable to successfully connect.

If you run the client program when the server does not start listening, the client will stop and print out the following error message: 对tcp 127.0.0.1:50000发起连接时产生错误:由于目标计算机的积极拒绝而无法创建连接.

You can start multiple client programs at the same time.

What is the output from the server:

C PS: \ the Users \ 20928 \ Go \ src \ go_code> Go RUN server.g erveo 
Starting at The Server ... 
Received data: Joe Smith says: Hello, my name is Zhang three 
Received data: John Doe says: Hello, my name four, nice to meet you 
Received data: Joe Smith says: where are you from? 
Received data: John Doe says: I come from China 
Received data: John Doe says: Beijing

In network programming  net.Dial function is very important, once you connect to a remote system, the function will return a  Conn type of interface, we can use it to send and receive data. Dial Simple functions abstracted network and transport layers. So whether it is IPv4 or IPv6, TCP or UDP can use this common interface.

 

 

Reference Links: https://github.com/unknwon/the-way-to-go_ZH_CN/blob/master/eBook/15.1.md

Guess you like

Origin www.cnblogs.com/lfri/p/11769254.html