dnssecsocket/example-gorilla/client.go

104 lines
2.4 KiB
Go

// Copyright 2015 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import "flag"
import "log"
import "net/url"
import "os"
import "os/signal"
import "time"
import "github.com/gorilla/websocket"
import "github.com/golang/protobuf/proto"
import pb "git.wit.com/wit/witProtobuf"
var addr = flag.String("addr", "v000185.testing.com.customers.wprod.wit.com:9000", "http service address")
func readConn(done chan struct{}, conn *websocket.Conn) {
defer close(done)
for {
mytype, message, err := conn.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
if (mytype == websocket.BinaryMessage) {
pdata := new(pb.Event)
err = proto.Unmarshal(message, pdata)
if (err != nil) {
log.Printf("readConn() something fucked up happened in Unmarshal")
}
log.Printf("recv binary: %s", pdata)
} else {
log.Printf("recv: %s", message)
// log.Printf("type, err = ", mytype, err)
}
}
}
func main() {
flag.Parse()
log.SetFlags(0)
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
u := url.URL{Scheme: "ws", Host: *addr, Path: "/echo"}
log.Printf("connecting to %s", u.String())
conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
}
defer conn.Close()
done := make(chan struct{})
// handle inbound messages on the channel
go readConn(done, conn)
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-done:
return
case t := <-ticker.C:
err := conn.WriteMessage(websocket.TextMessage, []byte(t.String()))
if err != nil {
log.Println("write:", err)
return
}
msg := pb.CreateSampleEvent()
msg.Name = "test echo over gorilla websocket"
data, _ := proto.Marshal(msg)
err2 := conn.WriteMessage(websocket.BinaryMessage, data)
if err2 != nil {
log.Println("write:", err2)
return
}
case <-interrupt:
log.Println("interrupt")
// Cleanly close the connection by sending a close message and then
// waiting (with timeout) for the server to close the connection.
err := conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("write close:", err)
return
}
select {
case <-done:
case <-time.After(time.Second):
}
return
}
}
}