一个极其简单的用golang net写的tcpip echoserver

前端之家收集整理的这篇文章主要介绍了一个极其简单的用golang net写的tcpip echoserver前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

@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]) }

猜你在找的Go相关文章