The test requires that a TCP Echo server was previously written with C + libevent, returning the server time, the client address information, and the original content sent by the client. For the sake of an article, now instead of Golang realization.
Package Mainimport ("FMT" "IO" "NET" "OS" "Time") const BUFFER_SIZE = 1024x768 * 4var BUFFER = make ([]byte, Buffer_size) func handle Connect (Tcpconn *net. Tcpconn) {if Tcpconn = = Nil {return}for {n, err: = Tcpconn.read (buffer) If err = = Io. EOF {fmt. Printf ("The remoteaddr:%s is closed!\n", tcpconn.remoteaddr (). String ()) Return}handleerror (err) if n > 0 {//fmt. Printf ("Read:%s", String (Buffer[:n])) str: = Tcpconn.remoteaddr (). String () + "@" +time. Now (). Format ("2006-01-02 15:04:05 z07:00") + "\ r \ n" +string (Buffer[:n]) tcpconn.write ([]byte (str)) FMT. Printf ("Echo:%s", str)}}}//error handling func handleError (err error) {if Err = = Nil {return}panic (err)//fmt. Printf ("Error:%s\n", err.) Error ())}func main () {if Len (OS. Args) < 2 {fmt. Println ("Usage:", OS.) Args[0], "<port>") Return}port: = OS. ARGS[1]TCPADDR, err: = Net. RESOLVETCPADDR ("TCP4", "0.0.0.0:" +port) HandleError (err) TcpListener, err: = Net. Listentcp ("TCP4", tcpaddr) HandleError (ERR) defer tcplistener.close () fmt. Println ("Listening on", Tcpaddr, "...") for {Tcpconn, err: = Tcplistener.accepttcp () fmt. PRINTF ("The client:%s has connected!\n", tcpconn.remoteaddr (). String ()) HandleError (ERR) defer tcpconn.close () go Handleconnect (tcpconn)}}
[UMU Study Golang] (3) TCP Echo Server