github.com/kaiya/goutils@v1.0.1-0.20230226104005-4ae4a4dc3688/tinyrpc/tcp-server.go (about) 1 package main 2 3 import ( 4 "bufio" 5 "fmt" 6 "net" 7 "os" 8 9 "github.com/kaiya/goutils/tinyrpc/rpc" 10 ) 11 12 const ( 13 CONN_HOST = "localhost" 14 CONN_PORT = "3333" 15 CONN_TYPE = "tcp" 16 ) 17 18 func main() { 19 // Listen for incoming connections. 20 l, err := net.Listen(CONN_TYPE, CONN_HOST+":"+CONN_PORT) 21 if err != nil { 22 fmt.Println("Error listening:", err.Error()) 23 os.Exit(1) 24 } 25 // Close the listener when the application closes. 26 defer l.Close() 27 fmt.Println("Listening on " + CONN_HOST + ":" + CONN_PORT) 28 for { 29 // Listen for an incoming connection. 30 conn, err := l.Accept() 31 if err != nil { 32 fmt.Println("Error accepting: ", err.Error()) 33 os.Exit(1) 34 } 35 // Handle connections in a new goroutine. 36 go handleRequest(conn) 37 } 38 } 39 40 // Handles incoming requests. 41 func handleRequest(conn net.Conn) { 42 defer conn.Close() 43 bufconn := bufio.NewReader(conn) 44 msg, err := rpc.DecodePacket(bufconn) 45 if err != nil { 46 fmt.Printf("decode packet error:%s\n", err) 47 return 48 } 49 50 fmt.Println("got msg len: ", len(msg)) 51 fmt.Println("msg: ", string(msg)) 52 }