[NodeJs] 웹소켓 사용하기
webSocket
웹소켓 연결
const WebSocket = require('ws');
const ws= new WebSocket('wss://websocket Address');
웹소켓 오픈
ws.onopen = function(event) {
}
ws.on('open', () => {
const data = {};
ws.send(JSON.stringify(data));
});
Header로 정보 보내기
const ws = new WebSocket("wss://websocket Address", {
headers: {
authorization: `Bearer "Auth Key.."`
}
});
메시지 수신
ws.onmessage = function (res) {
}
ws.on('message', (res) => {});
연결종료
ws.close(); // 웹소켙 종료
ws.on("close", () => {})
메시지전송
ws.send(Messages);
에러출력
ws.onerror = function(msg) {
console.log('socket error:' + msg.toString());
}
ws.on('error', (errorCode, errorMessage) => {
});
pingpong
참조 : https://stackoverflow.com/questions/26971026/handling-connection-loss-with-websockets
https://stackoverflow.com/questions/26971026/handling-connection-loss-with-websockets
일반적인 예
ws.on('pong', (mess) => { console.log(' receive a pong : '+mess); })
ws.timer=setInterval(() => {pingpong(ws);}, 10000);
function pingpong(ws) {
ws.ping('ping', {}, true);
} // end of pingpong
Bithumb 예
bithumb.on('open', () => {
setInterval(ping, 1000);
});
function ping() {
bithumb.send('__ping__');
// tm = setTimeout(function () {
// }, 5000);
}
function pong() {
// clearTimeout(tm);
}
ws.onmessage = function (evt) {
var msg = evt.data;
if (msg == '__pong__') {
pong();
return;
}
}
Statef
ws.readyState
SOCKET_CONNECTING = 0;
SOCKET_OPEN = 1;
SOCKET_CLOSING = 2;
SOCKET_CLOSED = 3;