1、socket通信
服务端接收数据
package main import ( "fmt" "net" "strings" ) func main() { //创建监听 ip := "127.0.0.1" port := 8848 address := fmt.Sprintf("%s:%d",ip,port) listen, err := net.Listen("tcp", address) if err != nil { fmt.Println(err) return } //一直轮询监听 for { fmt.Println("监听中...") //接收数据 conn, err := listen.Accept() if err != nil { fmt.Println("accept",err) return } fmt.Println("连接成功") //启动多个处理回调 go handle(conn) } } func handle(conn net.Conn) { for{ //创建一个容器,用于接受读取到的数据 buf := make([]byte,1024) //cnt真正读取客户端发来的数据长度 fmt.Println("准备读取发送过来的数据") cnt, err := conn.Read(buf) if err != nil { fmt.Println("cnt err",err) return } //只输出收到的长度 fmt.Println("长度:",cnt,"---数据:",string(buf[:cnt])) //将数据转成大写 upperData := strings.ToUpper(string(buf[:cnt])) write, err := conn.Write([]byte(upperData)) if err != nil { fmt.Println("write err",err) return } fmt.Println("长度:",write,"---数据:",upperData) } //关闭 conn.Close() }
socket客户端请求
func main() { dial, err := net.Dial("tcp", ":8848") if err != nil { panic(err) } fmt.Println("connect success") //不断重复发送多次 for { //发送数据 sendData := []byte("hello world") write, err := dial.Write(sendData) if err != nil { panic(err) } fmt.Println("send :",write,"--sendData:",string(sendData)) //接收服务器返回 buf := make([]byte,1024) read, err := dial.Read(buf) if err != nil { panic(err) } time.Sleep(time.Second) fmt.Println("client receive,",read,"--receive data:",string(buf[:read])) } defer dial.Close() }
2、http服务请求
服务端
func main() { //注册路由 http.HandleFunc("/user", func(writer http.ResponseWriter, request *http.Request) { //write 将数据返回给客户端 //request 请求数据 fmt.Println("method:",request.Method,request) io.WriteString(writer,"这是返回的数据") }) if err := http.ListenAndServe("127.0.0.1:8080",nil); err != nil { panic(err) } }
客户端请求
func main() { //http包 client := http.Client{} rsp, err := client.Get("http://127.0.0.1:8080") if err != nil { panic(err) } fmt.Println(rsp,rsp.Body,rsp.Header.Get("Content-Type")) }
请发表评论