Websocket Events
| event | handler | use |
|---|---|---|
| open | Socket.onopen | occurs when socket connection is established. |
| message | Socket.onmessage | occurs when client receives data from server. |
| error | Socket.onerror | occurs when there is any error in communication. |
| cloase | Socket.onclose | occurs when connection is closed. |
Methods
Socket.send()
The send(data) method transmits data using the connection.
Socket.close()
The close() method would be used to terminate any existing connection.
Examples
Base Example One
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:9998/echo");
ws.onopen = function() {
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function() {
// websocket is closed.
alert("Connection is closed...");
};
} else {
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Create a websocket object
In order to communicate using the WebSocket protocol, you need to create a WebSocket object; this will automatically attempt to open the connection to the server.
The WebSocket constructor accepts one required and one optional parameter:
/**
*
* url - wss: for secure ws for unsecure
* protocals - protocal string or array of protacal strings, used to create multiple connections
*
* /
webSocket = new WebSocket(url, protocols);
2
3
4
5
6
7
8
9
10
url The URL to which to connect; this should be the URL to which the WebSocket server will respond. This should use the URL scheme wss://, although some software may allow you to use the insecure ws:// for local connections. protocols Optional Either a single protocol string or an array of protocol strings. These strings are used to indicate sub-protocols, so that a single server can implement multiple WebSocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol). If you don't specify a protocol string, an empty string is assumed.
Example websocket helper
/*-------------------------------------------*\
ws.js
Class constructor to handle our real time subscription
functions and methods
\*-------------------------------------------*/
import tableDataInstance from '../Components/Table.js'
class WS {
constructor() {
this.socket = null
this.currentSubscriptions = []
this.socketList = []
this.resultData = []
}
/**
* CheckSocketConnection
*
* Checks if a socket connection already exists
* if not creates new
*
* @param {string} endpoint
*/
async createSocketConnection(endpoint) {
let checkSocket = WS.socket;
if (checkSocket) {
console.log("already connected")
return;
}
WS.socket = new WebSocket(`ws://localhost:8080/${endpoint}`);
// Handle any errors that occur.
WS.socket.onerror = function(error) {
console.log('WebSocket Error: ' + error);
};
// Show a connected message when the WebSocket is opened.
WS.socket.onopen = function(event) {
console.table(event)
console.log("succesfully connected")
return "succesfully connected";
};
WS.socket.onmessage = function(event) {
var msg = JSON.parse(event.data);
wsInstance.resultData.push(msg)
tableDataInstance.addRow(msg)
};
// Show a disconnected message when the WebSocket is closed.
WS.socket.onclose = function(event) {
console.log('Disconnected from WebSocket.')
};
}
/**
* handles websocket subscriptions
* @param{string} points - string of points, seperated by ,
*/
handleSubscriptions = (points) => {
wsInstance.resultData.splice(0, wsInstance.resultData.length)
tableDataInstance.switchDataSource()
//Unsubscribe to old points
if (this.currentSubscriptions.length > 0) {
this.currentSubscriptions.map(point => {
WS.socket.send(`unsubscribe ${point}`)
wsInstance.currentSubscriptions.pop();
})
}
if (!points) {
return console.log("no points sent")
}
const arrofPoints = points.split(",")
//Subscribe to new points
arrofPoints.map(point => {
WS.socket.send(`subscribe ${point}`)
wsInstance.currentSubscriptions.push(point)
return point
});
}
closeSocket = () => WS.socket.close();
}
const wsInstance = new WS();
Object.freeze(wsInstance);
export default wsInstance;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99