tcp服务器
package mainimport ( "fmt" "net")func main() { fmt.Println("启动服务器") // 创建 listener listener, err := net.Listen("tcp", "localhost:50000") if err != nil { fmt.Println("服务错误,终止服务", err.Error()) return //终止程序 } // 监听并接受来自客户端的连接 for { conn, err := listener.Accept() if err != nil { fmt.Println("错误的客户端请求", err.Error()) return // 终止程序 } go doServerStuff(conn) }}func doServerStuff(conn net.Conn) { for { buf := make([]byte, 512) len, err := conn.Read(buf) if err != nil { fmt.Println("读取客户端的请求错误", err.Error()) return //终止程序 } fmt.Printf("返回客户端传入的数据: %v", string(buf[:len])) }}创建了服务端我们还需要创建客户端:
package main import ( "bufio" "fmt" "net" "os" "strings" ) func main() { //打开连接: conn, err := net.Dial("tcp", "localhost:50000") if err != nil { //由于目标计算机积极拒绝而无法创建连接 fmt.Println("无法连接客户端", err.Error()) return // 终止程序 } inputReader := bufio.NewReader(os.Stdin) fmt.Println("请输入你的名字?") clientName, _ := inputReader.ReadString(\n) // fmt.Printf("CLIENTNAME %s", clientName) trimmedClient := strings.Trim(clientName, "\r\n") // Windows 平台下用 "\r\n",Linux平台下使用 "\n" // 给服务器发送信息直到程序退出: for { fmt.Println("发送Q中断连接") input, _ := inputReader.ReadString(\n) trimmedInput := strings.Trim(input, "\r\n") // fmt.Printf("input:--%s--", input) // fmt.Printf("trimmedInput:--%s--", trimmedInput) if trimmedInput == "Q" { return } _, err = conn.Write([]byte(trimmedClient + " says: " + trimmedInput)) } }我们先运行服务端
然后在运行客户端
执行结果:
接下来我们尝试搭建一个简单的http服务器
package main import ( "io" "net/http" ) /* handle a simple get request */ func Hello(w http.ResponseWriter, request *http.Request) { html:=`<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1>hello world</h1> </body> </html> ` io.WriteString(w, html) } func main() { http.HandleFunc("/hello", Hello) if err := http.ListenAndServe(":8000", nil); err != nil { panic(err) } }浏览器访问::8000/hello
但是当我们的http服务器出现错误时会执行panic导致直接停止了我们的web服务所有我们要增加这个错误的处理
package main import ( "io" "log" "net/http" ) type HandleFnc func(http.ResponseWriter, *http.Request) /* handle a simple get request */ func Hello(w http.ResponseWriter, request *http.Request) { html:=`<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1>hello world</h1> </body> </html> ` io.WriteString(w, html) } func logPanics(function HandleFnc) HandleFnc { return func(writer http.ResponseWriter, request *http.Request) { defer func() { if x := recover(); x != nil { log.Printf("[%v] caught panic: %v", request.RemoteAddr, x) } }() function(writer, request) } } func main() { http.HandleFunc("/hello", logPanics(Hello)) if err := http.ListenAndServe(":8000", nil); err != nil { panic(err) } }我们可以增加一个logPanics来处理我们的web服务遇到错误的情况