1 | /** |
||
2 | * Simple Websocket javascript |
||
3 | * @todo Live Data |
||
4 | * @description Don't miss data that changes even for a second |
||
5 | * @author Dimas Lanjaka <dimaslanjaka[at]gmail.com |
||
6 | * @see https://www.webmanajemen.com/p/simple-websocket.html Simple Web Socket |
||
7 | */ |
||
8 | var socket; |
||
9 | |||
10 | function socket_start(host) { |
||
11 | if (!host) { |
||
12 | console.error('Host websocket empty'); |
||
13 | return; |
||
14 | } |
||
15 | if (!socket_check()) { |
||
16 | console.log('WebSocket Started'); |
||
0 ignored issues
–
show
Debugging Code
introduced
by
![]() |
|||
17 | socket = socket_server(host); |
||
18 | } |
||
19 | try { |
||
20 | |||
21 | socket.onopen = function(msg) { |
||
0 ignored issues
–
show
|
|||
22 | console.log('socket initialized'); |
||
0 ignored issues
–
show
|
|||
23 | }; |
||
24 | socket.onmessage = function(msg) { |
||
25 | var data = JSON.parse(msg.data); |
||
26 | //do with data response |
||
27 | console.log(data); |
||
0 ignored issues
–
show
|
|||
28 | }; |
||
29 | |||
30 | socket.onclose = function(msg) { |
||
31 | console.log({ |
||
0 ignored issues
–
show
|
|||
32 | closed: socket |
||
0 ignored issues
–
show
|
|||
33 | }); |
||
34 | }; |
||
35 | } catch (ex) { |
||
36 | console.log(ex); |
||
37 | } |
||
38 | } |
||
39 | |||
40 | function socket_server(host) { |
||
41 | if (!host) { |
||
42 | console.error('Host websocket empty'); |
||
43 | return; |
||
0 ignored issues
–
show
Comprehensibility
Best Practice
introduced
by
|
|||
44 | } |
||
45 | console.log('Socket Initialized'); |
||
0 ignored issues
–
show
|
|||
46 | if (!window.EventSource) { |
||
47 | var socket = new EventSource(host); |
||
48 | } else { |
||
49 | |||
50 | var socket = new WebSocket(host); |
||
0 ignored issues
–
show
Comprehensibility
Naming
Best Practice
introduced
by
The variable
socket already seems to be declared on line 47 . Consider using another variable name or omitting the var keyword.
This check looks for variables that are declared in multiple lines. There may be several reasons for this. In the simplest case the variable name was reused by mistake. This may lead to very hard to locate bugs. If you want to reuse a variable for another purpose, consider declaring it at or near the top of your function and just assigning to it subsequently so it is always declared. ![]() |
|||
51 | } |
||
52 | return socket; |
||
53 | } |
||
54 | |||
55 | function socket_stop() { |
||
56 | if (socket != null) { |
||
57 | console.log("WebSocket Stopped"); |
||
0 ignored issues
–
show
|
|||
58 | socket.close(); |
||
59 | socket = null; |
||
60 | } |
||
61 | } |
||
62 | |||
63 | function socket_check() { |
||
64 | return socket; |
||
65 | } |