A Golang implementation TCP service example

Source: Internet
Author: User
Tags resolve ip address
This is a creation in Article, where the information may have evolved or changed.
Package Mainimport ("FMT" "Net" "Time" "OS" "Os/signal" "Sync") const (Workercount = 2) type Task str UCT {Id int32 Message string}var wg sync. Waitgroupvar Taskchannel = Make (chan Task) var signchannel = make (Chan os. Signal, 1) var exitchanel = make (chan int) func main () {go installsign () tcpaddr, err: = Net. RESOLVETCPADDR ("TCP4", "127.0.0.1:2202") if err! = Nil {Panic ("Resolve IP Address failed:" + Err. Error ())} FMT. Println ("Listening 127.0.0.1:2202 ...") listener, err: = Net. LISTENTCP ("TCP", TCPADDR) if err! = Nil {Panic ("Listen TCP failed:" + Err. Error ())} FMT. Println ("Listen success on 127.0.0.1:2202 with TCP4") defer func () {fmt. Println ("Close listenning ...") listener. Close () fmt. Println ("Shutdown")} () Connchannel: = Make (chan net.            Conn) go accept (listener, Connchannel) go handleconn (connchannel) go Taskdispatch () for {select { Case <-Signchannel:fmt. PRintln ("Get shutdown sign") go Notifygoroutingexit () goto EXIT}} exit:fmt . Println ("Waiting gorouting exit ....") WG. Wait ()}func Accept (listener * Net. TcpListener, Connchannel Chan net. Conn) {for {connection, err: = Listener. ACCEPTTCP () if err! = Nil {fmt. Println ("Accept failed:" + err.) Error ())} else {Connchannel <-connection}}}func handleconn (Connchannel Chan net. Conn) {fmt. PRINTLN ("wating connection ...") for {select {case conn: = <-Connchannel:remot EADDR: = conn. Remoteaddr () fmt. Println ("Client" + remoteaddr.string () + "Connected") Readconn (&conn)}}}func Readconn (con N *net. Conn) {for {(*conn)}. Setreaddeadline (time. Now (). ADD (5 * time. Second)) Buf: = Make ([]byte, 1024x768) _, Err: = (*conn). Read (BUF) if err! = Nil {fmt. Println ("Read ConneCtion Error: "+ Err. Error ()) If Err. Error () = = "EOF" {(*conn).                Close (); Fmt. PRINTLN ("Close connection" + (*conn). Remoteaddr (). String ()) Break}} if buf! = nil {fmt. Printf ("Read Message from Connect:%s", String (BUF)) Writeconn (conn, buf) var task task T Ask. Id = 1 task. Message = string (BUF) Taskchannel <-Task}}}func writeconn (conn *net. Conn, msg []byte) {_, Err: = (*conn). Write (msg) if err! = Nil {fmt. PRINTLN ("Write connection error:" + Err.) Error ()) If Err. Error () = = "EOF" {(*conn).            Close (); Fmt. PRINTLN ("Close connection" + (*conn). Remoteaddr (). String ())}}}func Taskdispatch () {fmt. PRINTLN ("Init task Moniter ....") for I: = 0; i < Workercount; i + + {go loop ()} FMT. PRINTLN ("Init task Moniter done!")} Func loop () {Ticker: = time. Newticker(Ten * time. SECOND) WG. ADD (1) defer func () {defer WG. Done () defer ticker. Stop ()} () for {fmt. PRINTLN ("wating task ...") Select {Case task: = <-taskchannel:fmt. Println ("task comming:" + task.)            Message) break; Case <-Exitchanel:fmt.         Println ("Woker get exit Sign") Goto STOP//default:}//Epoll, read the task data, do not need to handle timeout conditions Select {//Case <-Ticker. C://FMT. Println (time. Now ().        String () + "No task after ten second")//break; }} STOP://todo:clear undo Task}func Installsign () {signal. Notify (Signchannel, OS. Interrupt, OS. Kill)}func Notifygoroutingexit () {for i: = 0; i < workercount; I + + {Exitchanel <-1}}
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.