Tcp服务器端
package main
import (
“fmt”
“net”
)
func main() {
//监听
Listener,err:=net.Listen(“tcp”,“127.0.0.1:8888”)
if err != nil {
fmt.Printf(“err:=%+v\\n”,err)
return
}
defer Listener.Close()
//阻塞等待用户链
conn,err1:=Listener.Accept()
if err1 != nil {
fmt.Printf(“err:=%+v\\n”,err1)
}
defer conn.Close()
//设置一个缓冲切片,接收用户请求
buf := make([]byte,1024)
//读取缓冲的值read
n,err2:=conn.Read(buf)
if err2 != nil {
fmt.Printf(“err:=%+v\\n”,err2)
}
fmt.Println(“buf=”,string(buf[:n]))
defer conn.Close()
}
Tcp客户端
package main
import (
“fmt”
“net”
)
func main(){
//
conn,err:=net.Dial(“tcp”,“127.0.0.1:8888”)
if err != nil {
fmt.Printf(“err=%+v\\n”,err)
return
}
defer conn.Close()
//写入请求
conn.Write([]byte(“are you ok”))
}