0%

Web Socket 筆記

Web Socket Notes

Can I Use?
http://caniuse.com/#feat=websockets

Official
http://www.websocket.org/echo.html

Hello World

1
2
3
4
5
6
7
8
9
10
11
12
// client.js
var sock = new WebSocket("wss://echo.websocket.org");
sock.onopen = function (event) {
console.log('Connect!');
setTimeout(function () {
sock.send("hihi");
}, 5000);
}
sock.onmessage = function (event) {
console.log(event);
}

Socket io

Provide Server & Client
https://github.com/socketio/socket.io

WS

Server implementation for Node.js
https://github.com/websockets/ws

Connect to Server

npm install --save ws

1
2
3
4
5
6
// server/index.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({
port: 5000
});
1
2
3
4
5
// client.js
var sock = new WebSocket("ws://localhost:5000");
sock.onopen = function (event) {
console.log('Connect!');
}

Server receive message

1
2
3
4
5
6
7
8
9
10
11
12
// server/index.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({
port: 5000
});
wss.on('connection', function (ws) {
ws.on('message', function (data) {
console.log('Received: ' + data);
});
});
1
2
3
4
5
6
7
8
// client.js
var sock = new WebSocket("ws://localhost:5000");
sock.onopen = function (event) {
console.log('Connect!');
setTimeout(function () {
sock.send("hihi");
}, 1000);
}

Client receive message

1
2
3
4
5
6
7
8
9
10
11
12
// server/index.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({
port: 5000
});
wss.on('connection', function (ws) {
ws.on('message', function (data) {
ws.send("You sent: " + data);
});
});
1
2
3
4
5
6
7
8
// client.js
var sock = new WebSocket("ws://localhost:5000");
sock.onopen = function (event) {
console.log('Connect!');
}
sock.onmessage = function (event) {
console.log(event);
}