Update Iot.js
[platform/upstream/iotjs.git] / test / run_pass / test_dgram_broadcast.js
1 /* Copyright 2016-present Samsung Electronics Co., Ltd. and other contributors
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 var assert = require('assert');
17 var dgram = require('dgram');
18
19 var port = 41237;
20 var broadcast_address = '255.255.255.255';
21 var interval = 100;
22
23 var msg_count = 0, msg_count2 = 0, msg_count3 = 0, send_count = 0;
24
25 var msg = 'Hello IoT.js';
26 var socket = dgram.createSocket({type: 'udp4', reuseAddr: true});
27 var socket2 = dgram.createSocket({type: 'udp4', reuseAddr: true});
28 var socket3 = dgram.createSocket({type: 'udp4', reuseAddr: true});
29
30 socket.on('error', function(err) {
31   assert.fail();
32   socket.close();
33 });
34
35 socket2.on('error', function(err) {
36   assert.fail();
37   socket2.close();
38 });
39
40 socket3.on('error', function(err) {
41   assert.fail();
42   socket3.close();
43 });
44
45 socket.on('message', function(data, rinfo) {
46   console.log('socket got data : ' + data);
47   msg_count++;
48   if (msg_count == 3) {
49     socket.close();
50   }
51 });
52
53 socket2.on('message', function(data, rinfo) {
54   console.log('socket2 got data : ' + data);
55   msg_count2++;
56   if (msg_count2 == 3) {
57     socket2.close();
58   }
59 });
60
61 socket3.on('message', function(data, rinfo) {
62   console.log('socket3 got data : ' + data);
63   msg_count3++;
64   if (msg_count3 == 3) {
65     socket3.close();
66   }
67 });
68
69 socket.bind(port, function() {
70   socket.setBroadcast(true);
71   var timer = setInterval(function () {
72     send_count++;
73     socket.send(msg, port, broadcast_address);
74     if (send_count == 3) {
75       clearInterval(timer);
76     }
77   }, interval);
78 });
79
80 socket2.bind(port);
81
82 socket3.bind(port);
83
84 process.on('exit', function(code) {
85   assert.equal(code, 0);
86   assert.equal(msg_count, 3);
87   assert.equal(msg_count2, 3);
88   assert.equal(msg_count3, 3);
89   assert.equal(send_count, 3);
90 });