From 6a3257a9967723dd13497a5102bcba4e2ea0f1d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lucas=20L=C3=B6ffel?= Date: Tue, 9 Oct 2018 15:41:05 +0200 Subject: [PATCH] added example --- README.md | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/README.md b/README.md index dc26c09..2448782 100644 --- a/README.md +++ b/README.md @@ -3,3 +3,54 @@ [![Go Report Card](https://goreportcard.com/badge/github.com/loeffel-io/recws)](https://goreportcard.com/report/github.com/loeffel-io/recws) Reconnecting WebSocket is a websocket client based on [gorilla/websocket](https://github.com/gorilla/websocket) that will automatically reconnect if the connection is dropped. + +## Basic example + +```go +package main + +import ( + "context" + "github.com/loeffel-io/recws" + "log" + "time" +) + +func main() { + ctx, cancel := context.WithCancel(context.Background()) + ws := recws.RecConn{} + ws.Dial("wss://echo.websocket.org", nil) + + go func() { + time.Sleep(2 * time.Second) + cancel() + }() + + for { + select { + case <-ctx.Done(): + go ws.Close() + log.Printf("Websocket closed %s", ws.GetURL()) + return + default: + if !ws.IsConnected() { + log.Printf("Websocket disconnected %s", ws.GetURL()) + continue + } + + if err := ws.WriteMessage(1, []byte("Incoming")); err != nil { + log.Printf("Error: WriteMessage %s", ws.GetURL()) + return + } + + _, message, err := ws.ReadMessage() + if err != nil { + log.Printf("Error: ReadMessage %s", ws.GetURL()) + return + } + + log.Printf("Success: %s", message) + } + } +} +``` \ No newline at end of file