TCP 的C/S架构
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/284ce4dab45442ddbfd269a097bd08d5.png)
Server
package main
import (
"fmt"
"log"
"net"
"strings"
)
func dealConn(conn net.Conn) {
defer conn.Close()
ipAddr := conn.RemoteAddr().String()
fmt.Println(ipAddr, "连接成功")
buf := make([]byte, 1024)
for {
n, err := conn.Read(buf)
if err != nil {
fmt.Println(err)
return
}
result := buf[:n]
fmt.Printf("接收到数据来自[%s]==>[%d]:%s\n", ipAddr, n,
string(result))
if "exit" == string(result) {
fmt.Println(ipAddr, "退出连接")
return
}
conn.Write([]byte(strings.ToUpper(string(result))))
}
}
func main() {
listenner, err := net.Listen("tcp", "127.0.0.1:8000")
if err != nil {
log.Fatal(err)
}
defer listenner.Close()
for {
conn, err := listenner.Accept()
if err != nil {
log.Println(err)
continue
}
go dealConn(conn)
}
}
client
package main
import (
"bufio"
"fmt"
"log"
"net"
"os"
)
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:8000")
if err != nil {
log.Fatal(err)
return
}
defer conn.Close()
buf := make([]byte, 1024)
for {
fmt.Printf("请输入发送的内容:")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
buf = []byte(scanner.Text())
fmt.Printf("发送的内容:%s\n", string(buf))
conn.Write(buf)
n, err := conn.Read(buf)
if err != nil {
fmt.Println(err)
return
}
result := buf[:n]
fmt.Printf("接收到数据[%d]:%s\n", n, string(result))
}
}