...

How To use Wscat command with Golang websocket server?

Rate this post

What is wscat?

wscat is a command-line tool used to interact with WebSocket servers. Below is an example of using wscat to connect to a WebSocket server in Golang:

1. First, ensure you have wscat installed. You can install it via npm:

npm install -g wscat

2. Now, let’s create a basic WebSocket server in Golang:

# Create directory
mkdir websocketserver
# go inside this directory
cd websocketserver
# initialize go module
go mod init websocketserver

# Create main.go and add below code.

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

func echoHandler(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println(err)
        return
    }
    defer conn.Close()

    for {
        messageType, p, err := conn.ReadMessage()
        if err != nil {
            log.Println(err)
            return
        }
        if err := conn.WriteMessage(messageType, p); err != nil {
            log.Println(err)
            return
        }
    }
}

func main() {
    http.HandleFunc("/ws", echoHandler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

3. Build and run server

# install dependencies
go mod tidy

# build and run server
go build && ./websocketserver

The above command will build and run web socket server on port 8080

4. Use wscat to connect to the WebSocket server

Open another terminal or split terminal vertically and run the below command

wscat -c ws://localhost:8080/ws

Now you’re connected to the WebSocket server via wscat and can send and receive messages interactively.

5. Disconnect wscat from the server

Simply press ctrl+c to disconnect wscat from the server and end the current session.

Please see the below screenshot.

wscat example golang

Conclusion

In this post, you learnt about how to install wscat, how to create a simple websocketserver in go, and how to use wscat to interact with it.

Enjoy the post!!

Spread the love

Leave a Comment

Seraphinite AcceleratorOptimized by Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.