course/networkProgram/TCP/TCP_server.go

54 lines
900 B
Go
Raw Permalink Normal View History

2024-07-10 13:25:53 +08:00
package main
import (
"bufio"
"fmt"
"log"
"net"
"os"
"strings"
)
//TCP server端
func process(conn net.Conn) {
2024-07-10 19:46:50 +08:00
defer conn.Close()
2024-07-10 13:25:53 +08:00
var tmp = make([]byte, 1024)
reader := bufio.NewReader(os.Stdin)
for {
2024-07-10 19:46:50 +08:00
n, err := conn.Read(tmp)
2024-07-10 13:25:53 +08:00
if err != nil {
log.Fatal("read failed on:", err)
return
}
fmt.Println(string(tmp[:n]))
fmt.Print("请回复:")
msg, _ := reader.ReadString('\n')
msg = strings.TrimSpace(msg)
if msg == "exit" {
break
}
conn.Write([]byte(msg))
fmt.Println("等待回复中..")
}
}
func main() {
//1.本地端口启动服务
listener, err := net.Listen("tcp", "127.0.0.1:20000")
if err != nil {
log.Fatal("start Tcp server failed on:", err)
return
}
//2.等待别人来跟我建立链接
for {
conn, err := listener.Accept()
if err != nil {
log.Fatal("accept failed on:", err)
}
//3与客户端通信
go process(conn)
}
}