一、Go语言实现TCP通信
1、tcp服务端
一个TCP服务端可以同时连接很多个客户端,例如世界各地的用户使用自己电脑上的浏览器访问淘宝网。因为Go语言中创建多个goroutine实现并发非常方便和高效,所以我们可以每建立一次链接就创建一个goroutine去处理。
TCP服务端程序的处理流程:
- 监听端口
- 接收客户端请求建立链接
- 创建goroutine处理链接。
package main import ( "fmt" "net" "os" ) func errFunc(err error,info string){ if err !=nil{ fmt.Println(info,err) os.Exit(1) //将当前进程结束 } } func main(){ listen,err :=net.Listen("tcp","127.0.0.1:8000") errFunc(err,"connet net failed") defer listen.Close() conn,err :=listen.Accept() errFunc(err,"Accept err") defer conn.Close() buf :=make([]byte,4096) n,err :=conn.Read(buf) if n ==0{ return } errFunc(err,"conn Read") fmt.Println(string(buf[:n])) conn.Write([]byte(string(buf[:n]))) // 发送数据 }
http请求包:
请求行:请求方法(空格)请求文件URL(空格)协议版本
请求头:语法格式:key:value
空行:
---请求
请求包体