一個極其簡單的用golang net寫的tcpip echoserver
一個極其簡單的用golang net寫的tcpip echoserver
關鍵字:linux golang tcpip echoserver
雖然然效率不是很理想,但是可以給初學者參考
package main
import (
"fmt"
"net"
"os"
"runtime"
)
func doEcho(c net.Conn) {
defer c.Close()
for {
buf := make([]byte, 4096)
n, err := c.Read(buf[:])
if n == 0 || err != nil {
return
}
c.Write(buf[0:n])
}
}
func doStart(host string) {
if host == "" {
fmt.Println("Press input host name")
return
}
fmt.Println("Listening:" + host)
ln, err := net.Listen("tcp", host)
if err != nil {
fmt.Printf("Listen Error:")
return
}
defer ln.Close()
for {
c, err := ln.Accept()
if err != nil {
continue
}
doEcho(c)
}
}
func main() {
fmt.Println("CPU Num:", runtime.NumCPU())
runtime.GOMAXPROCS(runtime.NumCPU())
doStart(os.Args[1])
}