WebSocket using Golang

Inspired by the previous Article of Implementing WebSocket with NodeJS, I have tried successfully WebSocket in Go language.

Steps:

First install WebSocket package for Go:

go get github.com/gorilla/websocket

Start new project in Go, and write this HTML content in websockets.html file in project directory:

<!-- websockets.html -->
<h2>WebSocket using Golang</h2>
<h3>Server time</h3>
<pre id="output"></pre>
<script>

    var input = document.getElementById("input");
    var output = document.getElementById("output");
output.innerHTML = location.host;
    var socket = new WebSocket("ws://" + location.host + "/time");

    socket.onopen = function () {
        output.innerHTML = "Status: Connected";
    };

    socket.onmessage = function (e) {
        output.innerHTML = "From Server: <b>" + e.data + "</b>";
    };


</script>

</script>

Then write Go source code as main.go in the same directory of .HTML file :

// GorillaWebSocket project main.go
package main

import (
    "fmt"
    "net/http"
    "strconv"
    "time"

    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
    ReadBufferSize: 1024,
    WriteBufferSize: 1024,
}

var id = 0

func main() {
    http.HandleFunc("/time", timer)

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "websockets.html")
    })

    http.ListenAndServe(":1234", nil)
}

func timer(w http.ResponseWriter, r *http.Request) {

    conn, err := upgrader.Upgrade(w, r, nil)
    id++
    localID := id
    fmt.Println("Connected to: ", r.RemoteAddr, " as client # ", localID)
    fmt.Println(localID, r.UserAgent())
    if err != nil {
        fmt.Println("Error: ", err.Error())
    }

    for {

        time.Sleep(time.Second)
        now := time.Now()

        msg := "(" + strconv.Itoa(localID) + ") " + now.String()[:19]
        // Write time to browser
        err = conn.WriteMessage(websocket.TextMessage, []byte(msg))
        if err != nil {
            fmt.Println("Closed client # ", localID, ": Error: ", err.Error())
            return
        }
    }
}

Then run it and in the browser open

http://localhost:1234

You can open many tabs, or open many browsers or clients, and note that timer function will be instantiated with every client and it keeps working, which means every client will have it’s own running timer function, until the browser disconnects, then it will exist and will be removed from memory

Reference: https://gowebexamples.com/websockets/

11 thoughts on “WebSocket using Golang”

  1. Hello Motaz
    I tried to make client for this websocket server side, but connection reject by server side and return below message on log.
    Error: websocket: request origin not allowed by Upgrader.CheckOrigin
    because we need developing client site independent to server side.

  2. Hello Motaz
    I tried to make client for this websocket server side, but connection reject by server side and return below message on log.
    Error: websocket: request origin not allowed by Upgrader.CheckOrigin
    because we need developing client site independent to server side.

  3. Dear Mosab
    websocket.html contains the client script, and main.go is the server side of it,
    which one was missing in your testing?

    1. I have cloned websocket.html and ran it on other path, but i didn’t get response from server, when i return to server side log i get below message

      Error: websocket: request origin not allowed by Upgrader.CheckOrigin

      1. what did you mean by running it from other path?
        you have to run it from
        http://localhost:1234
        as in the article above
        If you miss any step from above it won’t work
        what is the browser type and version? did you tried it in Firefox or Chromium?
        what is the version of your Go compiler?
        Instead of copying the source from HTML article, you can download it to ensure that it is typical

        1. It works normally from url http://localhost:1234, but when i browse same websocket.html directly(double clicking html file) server reject request from this page.
          I mean if we use this websocket in project written in Java Servlet as a client and server side written in golang, is it going to work?

  4. I will work if you replace this line in websocket.html file:
    var socket = new WebSocket("ws://" + location.host + "/time");
    by:
    var socket = new WebSocket("ws://serverip:1234/time");
    Because first one will assume current port, and since you open it directly from browser it will use port 80, but you you open it from Go path it will assume port 1234

  5. I left may client sockets open in browsers for more than 24 hours without any disconnection, using Golang websocket application

Leave a Reply

Your email address will not be published. Required fields are marked *