Skip to content

Instantly share code, notes, and snippets.

@jensen
Created April 12, 2020 22:49
Show Gist options
  • Save jensen/ed85f4f24402f8e852494276cb761a3d to your computer and use it in GitHub Desktop.
Save jensen/ed85f4f24402f8e852494276cb761a3d to your computer and use it in GitHub Desktop.
Example websocket server/client with broken reconnect, fix it!
"use strict";
let websocket = require("websocket");
let url = "ws://localhost:8080";
let wsBitMex = new websocket.client();
let retries = 0;
function retryConnection() {
if (retries < 3) {
setTimeout(() => {
console.log("retrying connect");
wsBitMex.connect(url, "echo-protocol");
retries++;
retryConnection();
}, 3000);
}
}
/* bitmex wss feed*/
wsBitMex.on("connectFailed", function (error) {
console.log(`BitMex client connect error: ` + error.toString());
retryConnection();
});
wsBitMex.on("connect", function (connection) {
console.log(`BitMex webSocket client connected`);
retries = 0;
connection.on("error", function (error) {
console.log(`BitMex connection Error: ` + error.toString());
});
connection.on("close", function (error) {
console.log(`BitMex connection closed: ` + error.toString());
retryConnection();
});
connection.on("message", function (message) {
console.log(message);
});
});
wsBitMex.connect(url, "echo-protocol");
var WebSocketServer = require("websocket").server;
var http = require("http");
var server = http.createServer(function (request, response) {
console.log(new Date() + " Received request for " + request.url);
response.writeHead(404);
response.end();
});
server.listen(8080, function () {
console.log(new Date() + " Server is listening on port 8080");
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false,
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on("request", function (request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log(
new Date() + " Connection from origin " + request.origin + " rejected."
);
return;
}
var connection = request.accept("echo-protocol", request.origin);
console.log(new Date() + " Connection accepted.");
setInterval(() => {
connection.sendUTF("testing");
}, 2000);
connection.on("close", function (reasonCode, description) {
console.log(
new Date() + " Peer " + connection.remoteAddress + " disconnected."
);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment