一个极其简单的用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])
}
有疑问加站长微信联系(非本文作者)