@H_404_2@一个极其简单的用golang net写的tcpip echoserver
@H_404_2@
关键字: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]) }