14

Theres a websocket running in my localhost on ws://localhost:8080/ws

I need go lang code that can create a websocket client and connect to this server.

My Google-Fu skills failed to teach me a simple way to do this.

Thank you.

SudoPlz
  • 20,996
  • 12
  • 82
  • 123
  • Can you please provide a link with an example? I can't seem to find one that works with ping/pong etc.. – SudoPlz Sep 23 '15 at 20:53
  • I tried gorilla websocket, but theres NO documentation at all. At the moment I'm trying to implement the gorilla websocket client. – SudoPlz Sep 23 '15 at 20:54
  • 2
    There be [example client](https://github.com/gorilla/websocket/blob/master/examples/echo/client.go) in the GOrilla. – recoba Sep 23 '15 at 23:14
  • 1
    This example was added just a few days ago, so I wasn't aware of it. Thank you. – SudoPlz Sep 29 '15 at 15:16
  • 3
    I really liked the `Google-Fu` term used here... :-) – tgogos Oct 04 '17 at 10:39

2 Answers2

21

Nevermind I found some helping code online. Now my code looks like this in case someone else needs this:

package main

import (
        "net/http"
        "text/template"
        "code.google.com/p/go.net/websocket"
        "fmt"
        "os"
        "time"
)


const address string = "localhost:9999"

func main() {

    initWebsocketClient()
}


func initWebsocketClient() {
    fmt.Println("Starting Client")
    ws, err := websocket.Dial(fmt.Sprintf("ws://%s/ws", address), "", fmt.Sprintf("http://%s/", address))
    if err != nil {
        fmt.Printf("Dial failed: %s\n", err.Error())
        os.Exit(1)
    }
    incomingMessages := make(chan string)
    go readClientMessages(ws, incomingMessages)
    i := 0
    for {
        select {
        case <-time.After(time.Duration(2e9)):
            i++
            response := new(Message)
            response.RequestID = i
            response.Command = "Eject the hot dog."
            err = websocket.JSON.Send(ws, response)
            if err != nil {
                fmt.Printf("Send failed: %s\n", err.Error())
                os.Exit(1)
            }
        case message := <-incomingMessages:
            fmt.Println(`Message Received:`,message)


        }
    }
}

func readClientMessages(ws *websocket.Conn, incomingMessages chan string) {
    for {
        var message string
        // err := websocket.JSON.Receive(ws, &message)
        err := websocket.Message.Receive(ws, &message)
        if err != nil {
            fmt.Printf("Error::: %s\n", err.Error())
            return
        }
        incomingMessages <- message
    }
}

Also as recoba suggested in the comment, there has been a new gorilla example here for the ones looking for a better solution.

SudoPlz
  • 20,996
  • 12
  • 82
  • 123
6

Check out this event-based client, super easy: https://github.com/rgamba/evtwebsocket

Example:

package main

import (
    "fmt"

    "github.com/rgamba/evtwebsocket"

    "golang.org/x/net/websocket"
)

func main() {
  c := evtwebsocket.Conn{
    OnConnected: func(w *websocket.Conn) {
        fmt.Println("Connected")
    },
    OnMessage: func(msg []byte) {
        fmt.Printf("Received message: %s\n", msg)
    },
    OnError: func(err error) {
        fmt.Printf("** ERROR **\n%s\n", err.Error())
    },
  }
  // Connect
  c.Dial("ws://echo.websocket.org")
  c.Send([]byte("TEST"), nil)
}
Ricardo Gamba
  • 154
  • 1
  • 2