程序效果
image.png
程序代码:
utils.go
package utils
import (
"encoding/csv"
"fmt"
"io"
"os"
)
type csvReader struct {
FileName string
}
func NewCSVReader(fileName string) *csvReader {
reader := new(csvReader)
reader.FileName = fileName
return reader
}
func (cReader *csvReader) Read() [][]string {
file, err := os.Open(cReader.FileName)
if err != nil {
fmt.Println("Error:", err)
return nil
}
defer file.Close()
reader := csv.NewReader(file)
res := make([][]string, 0)
for {
record, err := reader.Read()
if err == io.EOF {
break
} else if err != nil {
fmt.Println("Error:", err)
return nil
}
res = append(res, record)
}
return res
}
type xiaoBin struct {
}
func NewXiaoBin() *xiaoBin {
x := new(xiaoBin)
return x
}
func (x *xiaoBin) MakeAnswers(strs [][]string) map[string]string {
res := make(map[string]string)
for _, line := range strs {
res[line[0]] = line[1]
}
return res
}
server.go
package main
import (
"fmt"
"golearn/tcpdemo2/server/utils"
"net"
"strings"
)
func Handle(conn net.Conn) {
for {
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
fmt.Printf("客户端关闭连接, %v!!\n", err)
return
}
strRecv := string(buf[:n])
// 本身带换行,不用加换行
fmt.Print(strRecv)
question := strings.Trim(strRecv, " \r\n")
// 加载CSV Answers
csvReader := utils.NewCSVReader("D:/csv/微软小冰.csv")
content := csvReader.Read()
xiaoBin := utils.NewXiaoBin()
answers := xiaoBin.MakeAnswers(content)
if answer, ok := answers[question]; !ok {
conn.Write([]byte("你说啥"))
} else {
conn.Write([]byte(answer))
}
}
}
func main() {
listen, err := net.Listen("tcp", "0.0.0.0:8888")
if err != nil {
fmt.Printf("创建TCP监听失败, %v!!\n", err)
return
}
defer listen.Close()
for {
conn, err := listen.Accept()
if err != nil {
fmt.Printf("接收客户端连接失败, %v!!\n", err)
}
go Handle(conn)
}
}
client.go
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
func main() {
conn, err := net.Dial("tcp", "192.168.3.6:8888")
if err != nil {
fmt.Printf("连接到服务器失败%v!!\n", err)
return
}
defer conn.Close()
for {
reader := bufio.NewReader(os.Stdin)
line, err := reader.ReadString('\n')
if err != nil {
fmt.Printf("从终端读取数据失败 %v!!\n", err)
return
}
line = strings.Trim(line, " \r\n")
if line == "exit" {
fmt.Println("您已确定退出客户端程序\n")
return
}
_, err = conn.Write([]byte(line + "\n"))
if err != nil {
fmt.Printf("向服务端写入数据失败%v!!\n", err)
}
answer := make([]byte, 1024)
n, err := conn.Read(answer)
if err != nil {
fmt.Printf("服务端关闭 %v!!\n", err)
return
}
fmt.Println(string(answer[:n]))
}
}
网友评论