示例#1
0
// This example demonstrates a trivial client.
func ExampleDial() {
	origin := "http://localhost/"
	url := "ws://localhost:12345/ws"
	ws, err := websocket.Dial(url, "", origin)
	if err != nil {
		log.Fatal(err)
	}
	if _, err := ws.Write([]byte("hello, world!\n")); err != nil {
		log.Fatal(err)
	}
	var msg = make([]byte, 512)
	var n int
	if n, err = ws.Read(msg); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Received: %s.\n", msg[:n])
}
示例#2
0
func TestEchoWebSocket(t *testing.T) {
	e := New()
	e.WebSocket("/ws", func(c *Context) error {
		c.socket.Write([]byte("test"))
		return nil
	})
	srv := httptest.NewServer(e)
	defer srv.Close()
	addr := srv.Listener.Addr().String()
	origin := "http://localhost"
	url := fmt.Sprintf("ws://%s/ws", addr)
	ws, err := websocket.Dial(url, "", origin)
	if assert.NoError(t, err) {
		ws.Write([]byte("test"))
		defer ws.Close()
		buf := new(bytes.Buffer)
		buf.ReadFrom(ws)
		assert.Equal(t, "test", buf.String())
	}
}