forked from mirror/websocket
Add closing handshake code to echo example client
This commit is contained in:
parent
361d4c0ffd
commit
844dd6d40e
|
@ -10,6 +10,8 @@ import (
|
||||||
"flag"
|
"flag"
|
||||||
"log"
|
"log"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
|
@ -21,6 +23,9 @@ func main() {
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
log.SetFlags(0)
|
log.SetFlags(0)
|
||||||
|
|
||||||
|
interrupt := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(interrupt, os.Interrupt)
|
||||||
|
|
||||||
u := url.URL{Scheme: "ws", Host: *addr, Path: "/echo"}
|
u := url.URL{Scheme: "ws", Host: *addr, Path: "/echo"}
|
||||||
log.Printf("connecting to %s", u.String())
|
log.Printf("connecting to %s", u.String())
|
||||||
|
|
||||||
|
@ -30,13 +35,16 @@ func main() {
|
||||||
}
|
}
|
||||||
defer c.Close()
|
defer c.Close()
|
||||||
|
|
||||||
|
done := make(chan struct{})
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
defer c.Close()
|
defer c.Close()
|
||||||
|
defer close(done)
|
||||||
for {
|
for {
|
||||||
_, message, err := c.ReadMessage()
|
_, message, err := c.ReadMessage()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("read:", err)
|
log.Println("read:", err)
|
||||||
break
|
return
|
||||||
}
|
}
|
||||||
log.Printf("recv: %s", message)
|
log.Printf("recv: %s", message)
|
||||||
}
|
}
|
||||||
|
@ -45,11 +53,29 @@ func main() {
|
||||||
ticker := time.NewTicker(time.Second)
|
ticker := time.NewTicker(time.Second)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
|
|
||||||
for t := range ticker.C {
|
for {
|
||||||
err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
|
select {
|
||||||
if err != nil {
|
case t := <-ticker.C:
|
||||||
log.Println("write:", err)
|
err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
|
||||||
break
|
if err != nil {
|
||||||
|
log.Println("write:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case <-interrupt:
|
||||||
|
log.Println("interrupt")
|
||||||
|
// To cleanly close a connection, a client should send a close
|
||||||
|
// frame and wait for the server to close the connection.
|
||||||
|
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
|
||||||
|
if err != nil {
|
||||||
|
log.Println("write close:", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
}
|
||||||
|
c.Close()
|
||||||
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue