1
+ /** Import dependecies */
1
2
import dgram from 'dgram' ;
2
3
import { Buffer } from 'buffer' ;
4
+
3
5
const socketPort : number = 8080 ;
6
+ const message = Buffer . from ( 'UDP CONNETION DATA' ) ;
4
7
8
+ /** Initialise UDP Socket */
5
9
const client = dgram . createSocket ( 'udp4' ) ;
6
- const message = Buffer . from ( 'UDP IOT CONNETION DATA' ) ;
7
10
8
- /** Listen and handle all incoming messages */
11
+ /** Listen and handle incoming messages from Server */
9
12
client . on ( 'message' , ( msg , info ) => {
10
13
console . log ( `Data received from server: ${ msg . toString ( ) } ` ) ;
11
14
console . log ( `Received ${ msg . length } bytes from ${ info . address } :${ info . port } \n` ) ;
12
15
} ) ;
13
16
14
- client . on ( 'listening' , function ( ) {
15
- var address = client . address ( ) ;
16
- console . log ( 'UDP Client listening on ' + address . address + ":" + address . port ) ;
17
- client . setBroadcast ( true ) ;
18
- } ) ;
19
-
20
17
/** Send message to Server */
21
18
client . send ( message , socketPort , 'localhost' , ( err ) => {
22
19
if ( err ) {
@@ -27,16 +24,21 @@ client.send(message, socketPort, 'localhost', (err) => {
27
24
}
28
25
} ) ;
29
26
30
- let intervalCount : number = 0 ;
31
- function sendMessage ( ) {
32
- client . send ( Buffer . from ( `Connection number ${ intervalCount } ` ) , socketPort , 'localhost' , ( err ) => {
33
- if ( err ) {
34
- console . log ( 'Error sending data to Server' )
35
- client . close ( ) ;
36
- } else {
37
- console . log ( 'Data sent to Server' )
38
- }
39
- } ) ;
40
- }
41
27
42
- // setInterval(sendMessage, 5000);
28
+ /**
29
+ * Send a message to the Server in an interval of every 5 seconds
30
+ * Enable this option by uncommenting
31
+ */
32
+
33
+ // let intervalCount: number = 0;
34
+ // function sendMessage() {
35
+ // client.send(Buffer.from(`Connection number ${intervalCount}`), socketPort, 'localhost', (err) => {
36
+ // if (err) {
37
+ // console.log('Error sending data to Server')
38
+ // client.close();
39
+ // } else {
40
+ // console.log('Data sent to Server')
41
+ // }
42
+ // });
43
+ // }
44
+ // setInterval(sendMessage, 5000);
0 commit comments