[UMU Study Golang] (3) TCP Echo Server

Source: Internet
Author: User

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

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.