golang的socket服务端与客户端
服务端
服务端的处理流程
- 监听端口
- 接收客户端的链接
- 创建goroutine,处理该链接
package main import ( "fmt" "net" ) func main() { fmt.Println("start server...") listen, err := net.Listen("tcp", "0.0.0.0:50000") if err != nil { fmt.Println("listen failed, err:", err) return } for { conn, err := listen.Accept()//监听是否有连接 if err != nil { fmt.Println("accept failed, err:", err) continue } go process(conn)//创建goroutine,处理连接 } } func process(conn net.Conn) { defer conn.Close() for { buf := make([]byte, 512) _, err := conn.Read(buf) if err != nil { fmt.Println("read err:", err) return } fmt.Println("read: ", string(buf)) } }
客服端
客户端的处理流程
- 建立与服务端的链接
- 进行数据收发
- 关闭链接
package main import ( "bufio" "fmt" "net" "os" "strings" ) func main() { conn, err := net.Dial("tcp", "localhost:50000") if err != nil { fmt.Println("Error dialing", err.Error()) return } defer conn.Close() inputReader := bufio.NewReader(os.Stdin) for { fmt.Println("请发送信息(退出请输入Q):") input, _ := inputReader.ReadString('\n') trimmedInput := strings.Trim(input, "\r\n") if trimmedInput == "Q" { return } _, err = conn.Write([]byte(trimmedInput)) if err != nil { return } } }
发送http请求
package main import ( "fmt" "io" "net" ) func main() { conn, err := net.Dial("tcp", "www.baidu.com:80") if err != nil { fmt.Println("Error dialing", err.Error()) return } defer conn.Close() msg := "GET / HTTP/1.1\r\n"//请求首行 msg += "Host: www.baidu.com\r\n"//请求头部 msg += "Connection: close\r\n"//请求头部 msg += "\r\n\r\n"//再下面是请求数据,这里没有携带数据 _, err = io.WriteString(conn, msg) if err != nil { fmt.Println("write string failed, ", err) return } buf := make([]byte, 4096) for { count, err := conn.Read(buf) if err != nil { break } fmt.Println(string(buf[0:count])) } }