Merge pull request #272 from terry-tt/main

go客户端
This commit is contained in:
ttttupup 2023-08-29 13:33:23 +08:00 committed by GitHub
commit 3b76b2332c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 55 additions and 0 deletions

11
go_client/main.go Normal file
View File

@ -0,0 +1,11 @@
package main
import (
"go_client/tcpserver"
"log"
)
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
tcpserver.Listen(19099)
}

View File

@ -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)
}
}