6f03661e745e020948025907e9df6565ba1e3027
[platform/upstream/iotjs.git] / tools / test / run_pass / test_dgram_1_server_1_client.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 = 41234;
20 var msg = 'Hello IoT.js';
21 var server = dgram.createSocket('udp4');
22
23 server.on('error', function(err) {
24   assert.fail();
25   server.close();
26 });
27
28 server.on('message', function(data, rinfo) {
29   console.log('server got data : ' + data);
30   console.log('client address : ' + rinfo.address);
31   console.log('client port : ' + rinfo.port);
32   console.log('client family : ' + rinfo.family);
33   assert.equal(data, msg);
34   server.send(msg, rinfo.port, 'localhost', function (err, len) {
35     assert.equal(err, null);
36     assert.equal(len, msg.length);
37     server.close();
38   });
39 });
40
41 server.on('listening', function() {
42   console.log('listening');
43 });
44
45 server.bind(port);
46
47 var client = dgram.createSocket('udp4');
48
49 client.send(msg, port, 'localhost', function(err, len) {
50   assert.equal(err, null);
51   assert.equal(len, msg.length);
52 });
53
54 client.on('error', function(err) {
55   assert.fail();
56   client.close();
57 });
58
59 client.on('message', function(data, rinfo) {
60   console.log('client got data : ' + data);
61   console.log('server address : ' + rinfo.address);
62   console.log('server port : ' + rinfo.port);
63   console.log('server family : ' + rinfo.family);
64   assert.equal(port, rinfo.port);
65   assert.equal(data, msg);
66   client.close();
67 });
68
69 process.on('exit', function(code) {
70   assert.equal(code, 0);
71 });