dial a websocket
parent
3d04042c88
commit
9abaf5a252
@ -0,0 +1,55 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/jordanorelli/blammo"
|
||||
)
|
||||
|
||||
type client struct {
|
||||
*blammo.Log
|
||||
host string
|
||||
port int
|
||||
}
|
||||
|
||||
func (c *client) run() {
|
||||
dialer := websocket.Dialer{
|
||||
HandshakeTimeout: 3 * time.Second,
|
||||
ReadBufferSize: 32 * 1024,
|
||||
WriteBufferSize: 32 * 1024,
|
||||
Subprotocols: []string{"astrodomu@v0"},
|
||||
}
|
||||
|
||||
path := url.URL{
|
||||
Host: fmt.Sprintf("%s:%d", c.host, c.port),
|
||||
Scheme: "ws",
|
||||
Path: "/",
|
||||
}
|
||||
|
||||
conn, res, err := dialer.Dial(path.String(), nil)
|
||||
if err != nil {
|
||||
c.Error("dial error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Debug("dial response status: %d", res.StatusCode)
|
||||
for k, vals := range res.Header {
|
||||
c.Debug("dial response header: %s = %s", k, strings.Join(vals, ","))
|
||||
}
|
||||
|
||||
for {
|
||||
w, err := conn.NextWriter(websocket.TextMessage)
|
||||
if err != nil {
|
||||
c.Error("unable to get a websocket frame writer: %v", err)
|
||||
break
|
||||
}
|
||||
|
||||
w.Write([]byte("hey"))
|
||||
w.Close()
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/jordanorelli/blammo"
|
||||
)
|
||||
|
||||
type server struct {
|
||||
*blammo.Log
|
||||
host string
|
||||
port int
|
||||
}
|
||||
|
||||
func (s *server) listen() error {
|
||||
return http.ListenAndServe(fmt.Sprintf("%s:%d", s.host, s.port), s)
|
||||
}
|
||||
|
||||
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
upgrader := websocket.Upgrader{}
|
||||
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
s.Error("upgrade error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
t, r, err := conn.NextReader()
|
||||
if err != nil {
|
||||
s.Error("read error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
switch t {
|
||||
case websocket.TextMessage:
|
||||
text, err := ioutil.ReadAll(r)
|
||||
if err != nil {
|
||||
s.Error("readall error: %v", err)
|
||||
break
|
||||
}
|
||||
s.Info("received: %s", text)
|
||||
case websocket.BinaryMessage:
|
||||
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue