多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
``` package main import ( "fmt" "net" ) func HandlerConnect(conn net.Conn) { defer conn.Close() //1.获取客户端ip地址 addr := conn.RemoteAddr() fmt.Println("client ip : ", addr) //2.循环读取客户端发送数据 buf := make([]byte, 4096) for{ n, err := conn.Read(buf) if err != nil { fmt.Println("conn read err : ", err) return } if n == 0 { fmt.Println("检测到客户端已关闭, 断开连接") } if "exit\n" == string(buf[:n]) || "exit\r\n" == string(buf[:n]) { fmt.Println("接收到客户端退出请求") return } fmt.Println("client said : ", string(buf[:n])) conn.Write([]byte(string(buf[:n]))) } } func main() { lisenter, err := net.Listen("tcp", "127.0.0.1:8080") if err != nil{ fmt.Println("listen err : ", err) return } defer lisenter.Close() for { fmt.Println("服务器等待客户端连接.....") conn, err := lisenter.Accept() if err!=nil { fmt.Println("accept err : ", err) return } go HandlerConnect(conn) } } ```