AngularJS WebSocket JSONデータ送信サンプルコード

ウェブソケットAPIによるサーバ側へのJSONフォーマットによるデータ送信サンプルコード

The standard client-side API

The W3C describes the WebSocket object and methods that are now standard on all browsers.

An instance is declared with the URL for parameter containing the ws: protocol for a simple connection or wss: for a secure connection.

var ws = new WebSocket(“ws://www.example.com”);

It could also be a local connection, in this case we also specify the port, for example 8100.

var ws = new WebSocket(“ws://localhost:8100”);

The object sends data to the server as a string with the send method.

ws.send(“Hello server…”);

But it also allows you to send structured data, simply convert them to a string for the transmission.

var data = { “type” : “text”, “message” : “Hello” };
var message = JSON.stringify(data);
ws.send(message);