首页  

go socket 编程 echo server     所属分类 go 浏览量 81
注意字符串不能和数字直接拼接
str := "Starting the server,port="+strconv.Itoa(port)
切片转字符串 string(buf)

go run echo-server.go -port=8888


package main import ( "net" "fmt" "io" "flag" "strconv" ) func main() { var port int flag.IntVar(&port, "port", 8888, "port") flag.Parse() listener, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(port)) if err != nil { panic("error listen: " + err.Error()) } fmt.Println("Starting the server,port="+strconv.Itoa(port)) for { conn, err := listener.Accept() if err != nil { panic("error accept: " + err.Error()) } fmt.Println("Accept the connection: ", conn.RemoteAddr()) go echoServer(conn) } } func echoServer(conn net.Conn) { buf := make([]byte, 1024) defer conn.Close() for { n, err := conn.Read(buf) switch err { case nil: conn.Write(buf[0:n]) case io.EOF: fmt.Printf("Warning: End of data %s\n", err) return default: fmt.Printf("Error: read data %s\n", err) return } fmt.Println(conn.RemoteAddr(),string(buf)) } }
https://gitee.com/dyyx/hellocode/blob/master/web/tech/go/demo/echo-server.go

上一篇     下一篇
开公司要知道的财税制度

GO panic recover

GO字符串拼接

java HTTP Server NanoHttpd

java nio echo server

GO文件读取