Skip to content

Commit

Permalink
feat: Add logout signal and quit command
Browse files Browse the repository at this point in the history
- Add support for logout signal and quit command to gracefully exit
- Improve logging by filtering out sensitive message using a map

#17
  • Loading branch information
lc-1010 committed Jul 28, 2023
1 parent a2b53a4 commit 9c6fbae
Showing 1 changed file with 56 additions and 17 deletions.
73 changes: 56 additions & 17 deletions chatroom/cmd/websocket/gobwas/client/clinet.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ package main
import (
"bufio"
"context"
"fmt"
"io"
"log"
"os"
"os/signal"
"time"

"github.com/gobwas/ws"
Expand All @@ -18,37 +21,73 @@ func main() {
if err != nil {
log.Fatal(err)
}
defer conn.Close()

err = wsutil.WriteClientText(conn, []byte("Hello WebSocket server"))
if err != nil {
log.Panicln(err)
}

c := make(chan os.Signal, 1)
scanner := bufio.NewScanner(os.Stdin)

data := make(chan string)
hasClosed := map[string]bool{"hasClosed": false}
go func() {
defer close(data)
for {
msg, _, err := wsutil.ReadServerData(conn)
//这里是for 等待所以会造成阻塞 所以无法主动退出
if err != nil {
log.Panicln(err)
if err == io.EOF {
log.Println("server say bye")
c <- os.Kill
return
} else {
if !hasClosed["hasClosed"] {
log.Printf(" err:%v", err)
} else {
return
}
}
} else {
data <- string(msg)
}
log.Printf(">> %v\n", string(msg))

}

}()

scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
input := scanner.Bytes()
if err := wsutil.WriteClientText(conn, input); err != nil {
log.Printf("NewScanner %v\n", err)
go func() {
for scanner.Scan() {
input := scanner.Bytes()
if string(input) == "quit" {
log.Println("ok will quit wait...")
c <- os.Kill
return
}
if err := wsutil.WriteClientText(conn, input); err != nil {
log.Printf("NewScanner %v\n", err)
return
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}()

signal.Notify(c, os.Interrupt)
t:
for {
select {
case msg := <-data:
fmt.Printf(">: %v\n", msg)
case <-c:
hasClosed["hasClosed"] = true
break t
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}

defer conn.Close()
}
log.Println("ok bye")

// func mustCopy(dst io.Writer, src io.Reader) {
// if _, err := io.Copy(dst, src); err != nil {
// log.Fatal(err)
// }
// }
}

0 comments on commit 9c6fbae

Please sign in to comment.