go-tcp

go-tcp编程学习:

服务端代码:

package main

import (
"fmt"
"net"
)

func process(coon net.Conn) {

//创建一个切片
buf := make([]byte, 1024)

defer coon.Close()

//循环接收客户端发送的信息
for {
n, err := coon.Read(buf)
if err != nil {
fmt.Println("coon Read err=", err)
return
}

//显示信息
fmt.Print(string(buf[:n]))
}
}

func main() {

//Go--tcp编程
listen, err := net.Listen("tcp", "0.0.0.0:8888")
if err != nil {
//监听失败
fmt.Println("listen err=", err)
return
}

defer listen.Close()

//循环等待客户端的连接
for {
coon, err := listen.Accept()
if err != nil {
fmt.Println("Accept() err=", err)
} else {
fmt.Printf("Accept success, clientIp=%v\n", coon.RemoteAddr().String())
}

//起一个协程服务于客户端
go process(coon)
}

}

客户端代码:

package main

import (
"fmt"
"net"
"bufio"
"os"
"strings"
)

func main() {

//client
coon, err := net.Dial("tcp", "127.0.0.1:8888")
if err != nil {
fmt.Println("net.Dial err=", err)
return
}

//创建一个reader
reader := bufio.NewReader(os.Stdin)

//循环进行用户输入
for {

//从终端读取一行
line, err := reader.ReadString('\n')
if err != nil {
fmt.Println("readString err=", err)
}

//判断是否退出
line = strings.Trim(line, " \r\n")
if line == "exit" {
fmt.Printf("client %s exit", coon.RemoteAddr().String())
break
}

//将数据发送给服务端
_, err = coon.Write([]byte(line + "\n"))
if err != nil {
fmt.Println("coon.Write err=", err)
}
}
}

效果:

posted @ 2019-11-18 10:39  水滴月  阅读(232)  评论(0编辑  收藏  举报