Upload packaging folder
[platform/upstream/iotjs.git] / test / run_pass / test_dgram_1_server_n_clients.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 = 41235;
20 var msg = '';
21 var sockcount = 5;
22 var sendcount = 0;
23 var server = dgram.createSocket('udp4');
24
25 server.on('error', function(err) {
26   assert.fail();
27   server.close();
28 });
29
30 server.on('message', function(data, rinfo) {
31   console.log('server got data : ' + data);
32   msg += data;
33
34   server.send(data, rinfo.port, 'localhost', function (err, len) {
35     sendcount++;
36     if (sendcount >= sockcount) {
37       server.close();
38     }
39   });
40 });
41
42 server.bind(port);
43
44 for (var i = 0; i < sockcount; i++) {
45   (function sendAndRecieve(i) {
46     var client = dgram.createSocket('udp4');
47
48     client.send(i.toString(), port, 'localhost');
49
50     client.on('error', function(err) {
51       assert.fail();
52       client.close();
53     });
54
55     client.on('message', function(data, rinfo) {
56       console.log('client got data : ' + data);
57       assert.equal(port, rinfo.port);
58       assert.equal(data, i.toString());
59       client.close();
60     });
61   })(i);
62 }
63
64 process.on('exit', function(code) {
65   assert.equal(msg.length, sockcount);
66   for (var i = 0; i < sockcount; i++) {
67       if (msg.indexOf(i.toString()) == -1) {
68         assert.fail();
69       }
70   }
71   assert.equal(code, 0);
72 });