User Tools

Site Tools


web_socket_server

Web Socket output

  • Web Socket output option is a client that sends JSON lines to web socket server
  • The advantages of web socket server are very low latency and ability to pass firewalls and proxy servers because data is HTTP compliant and this is a push method (client pushes data to server)
  • Advantage of JSON is small size

Syntax to be used in Scoreboard OCR:

ws://host:port/id
ws://localhost:15001/stream1

Command sent when creating new connection:

{"type":"register", "stream":"stream1", "role":"ocr"}

Command sent when updating data:

{“type”:”ocr”, “values”:{"field_name": “value”, "field_name2": “value”}}
{“type”:”ocr”, “values”:{"time": “3:12”, "score_a": “56”}}

Websocket server golang sample

In order to make this method work, you will need a websocket server. Here we have an example of golang code that you can use to create a websocket server:

package main

import (
	"fmt"
	"net/http"

	"github.com/gorilla/websocket"
)

func main() {
	http.HandleFunc("/", wsHandler)

	panic(http.ListenAndServe(":15001", nil))
}

func wsHandler(w http.ResponseWriter, r *http.Request) {
	conn, err := websocket.Upgrade(w, r, w.Header(), 1024, 1024)
	if err != nil {
		http.Error(w, "Could not open websocket connection", http.StatusBadRequest)
	}

	go handleData(conn)
}

func handleData(conn *websocket.Conn) {
	defer conn.Close()
	for {
		_, b, err := conn.ReadMessage()

		if err != nil {
			fmt.Println("Error reading json.", err)
			break
		}

		fmt.Printf("Got message: %v\n", string(b))

		if string(b) == `{"type":"ping"}` {
			conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"pong"}`))
		}
	}
}
web_socket_server.txt · Last modified: 2018/11/04 16:26 by arturs