Skip to content

Commit a3ef3eb

Browse files
committed
add hello-ws project
1 parent 0f7073d commit a3ef3eb

File tree

3 files changed

+94
-0
lines changed

3 files changed

+94
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
{
2+
"version": "0.2.0",
3+
"configurations": [
4+
{
5+
"name": "Start",
6+
"type": "node",
7+
"request": "launch",
8+
"program": "${workspaceRoot}/app.js",
9+
"stopOnEntry": false,
10+
"args": [],
11+
"cwd": "${workspaceRoot}",
12+
"preLaunchTask": null,
13+
"runtimeExecutable": null,
14+
"runtimeArgs": [
15+
"--nolazy"
16+
],
17+
"env": {
18+
"NODE_ENV": "development"
19+
},
20+
"externalConsole": false,
21+
"sourceMaps": false,
22+
"outDir": null
23+
}
24+
]
25+
}

samples/node/web/ws/hello-ws/app.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
const WebSocket = require('ws');
2+
3+
const WebSocketServer = WebSocket.Server;
4+
5+
const wss = new WebSocketServer({
6+
port: 3000
7+
});
8+
9+
wss.on('connection', function (ws) {
10+
console.log(`[SERVER] connection()`);
11+
ws.on('message', function (message) {
12+
console.log(`[SERVER] Received: ${message}`);
13+
setTimeout(() => {
14+
ws.send(`What's your name?`, (err) => {
15+
if (err) {
16+
console.log(`[SERVER] error: ${err}`);
17+
}
18+
});
19+
}, 1000);
20+
})
21+
});
22+
23+
console.log('ws server started at port 3000...');
24+
25+
// client test:
26+
27+
let count = 0;
28+
29+
let ws = new WebSocket('ws://localhost:3000/ws/chat');
30+
31+
ws.on('open', function () {
32+
console.log(`[CLIENT] open()`);
33+
ws.send('Hello!');
34+
});
35+
36+
ws.on('message', function (message) {
37+
console.log(`[CLIENT] Received: ${message}`);
38+
count++;
39+
if (count > 3) {
40+
ws.send('Goodbye!');
41+
ws.close();
42+
} else {
43+
setTimeout(() => {
44+
ws.send(`Hello, I'm Mr No.${count}!`);
45+
}, 1000);
46+
}
47+
});
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"name": "hello-ws",
3+
"version": "1.0.0",
4+
"description": "Hello WebSocket example",
5+
"main": "start.js",
6+
"scripts": {
7+
"start": "node app.js"
8+
},
9+
"keywords": [
10+
"ws",
11+
"websocket"
12+
],
13+
"author": "Michael Liao",
14+
"license": "Apache-2.0",
15+
"repository": {
16+
"type": "git",
17+
"url": "https://github.com/michaelliao/learn-javascript.git"
18+
},
19+
"dependencies": {
20+
"ws": "1.1.1"
21+
}
22+
}

0 commit comments

Comments
 (0)