Go语言之进阶篇TCP相互通信

1、TCP相互通信

服务端示例:

tcp_server.go

package main

import (
	"fmt"
	"net"
)

func main() {
	//监听
	listener, err := net.Listen("tcp", "127.0.0.1:8000")
	if err != nil {
		fmt.Println("err = ", err)
		return
	}

	defer listener.Close()

	//阻塞等待用户链接
	conn, err := listener.Accept()
	if err != nil {
		fmt.Println("err = ", err)
		return
	}

	//接收用户的请求
	buf := make([]byte, 1024) //1024大小的缓冲区
	n, err1 := conn.Read(buf)
	if err1 != nil {
		fmt.Println("err1 = ", err1)
		return
	}

	fmt.Println("buf = ", string(buf[:n]))

	defer conn.Close() //关闭当前用户链接
}

客户端示例:

tcp_client.go

package main

import (
	"fmt"
	"net"
)

func main() {
	//主动连接服务器
	conn, err := net.Dial("tcp", "127.0.0.1:8000")
	if err != nil {
		fmt.Println("err = ", err)
		return
	}

	defer conn.Close()

	//发送数据
	conn.Write([]byte("are you ok?"))

}

先启动服务端:go run tcp_server.go

D:\GoFiles\src\hello_01>go run tcp_server.go
buf =  are u ok?

再启动客户端:go run tcp_client.go

 

posted @ 2019-01-21 17:26  努力哥  阅读(3154)  评论(0编辑  收藏  举报