Golang TCP Echo Server sample

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

Golang Code Server:

Package Mainimport (//"IO" "Log" "NET" "Time" "FMT" "Runtime") func main () {runtime. Gomaxprocs (4)//Set the number of CPUs//Listen on TCP Port # on all interfaces. L, Err: = Net. Listen ("TCP", ":") if err! = Nil {  log. Fatal (ERR)} defer L.close () for {  conn, err: = L.accept ()  if err! = Nil {   log. Fatal (Err)  }  //Handle The connection in a new goroutine.  The loop then returns to accepting and so  //multiple connections is served concurrently.  Go func (c net. Conn) {   defer c.close ()   var buf = make ([]byte, MB)   for {    cnt, err: = C.read (BUF)    if err! = Nil { C14/>fmt. Printf ("Recv failed:%s", err)     return    }       //fmt. Println (String (buf[:cnt)) time    . Sleep    _, Err = C.write (buf[:cnt])    if err! = Nil {     FMT. Printf ("Write failed:%s", err)     return    }}}  (conn)}}


Client Python code:

Import Threadingimport sysimport timeimport socket, Sysimport selectdef Echo ():    host = "172.16.2.18"    Textport = 2    s = socket.socket (socket.af_inet, socket. Sock_stream)    Try:        port = Int (textport)    except valueerror:        port = socket.getservbyname (Textport, ' TCP ')    S.connect ((host, Port)) while    1:        select.select ([],[],[],0.1)        data = Time.ctime ()        Data.join ("\ r \ n")        S.sendall (data)        #print "looking for replies; Press CTRL-C or Ctrl-break to stop. "        BUF = S.RECV (2048)    if __name__ = = "__main__":    threads = [] for    i in xrange:        OS = threading. Thread (None,echo)        Os.start ()        threads.append (OS) for        x in Threads:        x.join ()


Related Article

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.