From d8c8078f5c87dba9ca98802f9aa1bd3039580f53 Mon Sep 17 00:00:00 2001 From: litao Date: Tue, 29 Aug 2023 11:25:15 +0800 Subject: [PATCH] =?UTF-8?q?go=E5=AE=A2=E6=88=B7=E7=AB=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go_client/main.go | 11 ++++++++ go_client/tcpserver/tcpserver.go | 44 ++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 go_client/main.go create mode 100644 go_client/tcpserver/tcpserver.go diff --git a/go_client/main.go b/go_client/main.go new file mode 100644 index 0000000..6859a43 --- /dev/null +++ b/go_client/main.go @@ -0,0 +1,11 @@ +package main + +import ( + "go_client/tcpserver" + "log" +) + +func main() { + log.SetFlags(log.LstdFlags | log.Lshortfile) + tcpserver.Listen(19099) +} diff --git a/go_client/tcpserver/tcpserver.go b/go_client/tcpserver/tcpserver.go new file mode 100644 index 0000000..edee43b --- /dev/null +++ b/go_client/tcpserver/tcpserver.go @@ -0,0 +1,44 @@ +package tcpserver + +import ( + "bufio" + "log" + "net" + "strconv" +) + +func Listen(port int) { + p := strconv.Itoa(port) + adress := "127.0.0.1:" + p + ln, err := net.Listen("tcp", adress) + if err != nil { + log.Fatal(err) + } + defer ln.Close() + log.Println("tcp server started") + for { + conn, err := ln.Accept() + if err != nil { + log.Println(err) + continue + } + go handle(conn) + } +} + +func handle(conn net.Conn) { + defer func() { + if err := recover(); err != nil { + log.Println("发生了未处理的异常", err) + } + }() + defer conn.Close() + scanner := bufio.NewScanner(conn) + for scanner.Scan() { + line := scanner.Bytes() + log.Println("收到消息:", string(line)) + } + if err := scanner.Err(); err != nil { + log.Println("错误:", err) + } +}