Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
#!/usr/bin/env node
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 autoAcceptwssockets 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
});
wsServer.binaryType = 'arraybuffer';
//wsServer.setEncoding('binary');
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
}).on('error', (err) => {
// handle errors here
setTimeout( serverStartListening, 500);
});
serverStartListening = function() {
server.listen(30035, function() {
console.warn((new Date()) + ' Server is listening on port 30035');
});
};
var wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
var clients = {};
var connection;
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
request.reject();
console.log( (new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
console.log("AutoParsed (1):", auto, data);
}
} catch (err) {
console.log(err);
console.log("AutoParsed (2):", auto, data);
}
}
} catch (err) {
console.log(err);
}
};
/**
* WebSocket server
*/
var wsServer = new webSocketServer({
// WebSocket server is tied to a HTTP server. WebSocket request is just
// an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6
httpServer: server
});
// This callback function is called every time someone
// tries to connect to the WebSocket server
wsServer.on('request', function(request) {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
// accept connection - you should check 'request.origin' to make sure that
// client is connecting from your website
// (http://en.wikipedia.org/wiki/Same_origin_policy)
var connection = request.accept(null, request.origin);
clients.push(connection);
console.log((new Date()) + ' Connection accepted.');
'WS' : function () {
var addr = self.transport.toLowerCase() +
'://' + self.target + ':' + self.port;
if (self.wsPath) {
addr += '/' + self.wsPath;
}
self.megaSocket = new WebSocketClient({
tlsOptions : {
rejectUnauthorized : false
}
});
setTimeout(timeoutCb, self.timeout);
self.megaSocket.on('connectFailed', function (err) {
received = true; // to avoid the launch of our timeout error
if (!wsError) {
self.emit('error', {
type : 'socket: connectFailed',
data : err.toString()
});
}
});
if (typeof server.config.token === 'function') {
// server.config.token is a function, call it periodically to renew the token
tokenRenewDuration = new moment.duration(1, 'hours');
token = server.config.token();
} else {
// server.config.token is a string, the token cannot be renewed automatically
token = server.config.token;
}
headers = { 'ServiceBusAuthorization': token };
};
// This represents the token renew timer/interval, keep a reference in order to cancel it.
var tokenRenewTimer = null;
var client = new WebSocketClient();
client.connect(server.listenUri, null, null, headers);
client.on('connect', function(connection) {
server.controlChannel = connection;
server.controlChannel.on('error', function(event) {
server.emit('error', event);
clearInterval(tokenRenewTimer);
if (!closeRequested) {
connectControlChannel(server);
}
});
server.controlChannel.on('close', function(event) {
clearInterval(tokenRenewTimer);
if (!closeRequested) {
// reconnect
connectControlChannel(server);
function startReceivingW3CWebSocketClient(streamUrl, conversationId) {
console.log('Starting W3C WebSocket Client for message streaming on conversationId: ' + conversationId);
var ws = new (require('websocket').w3cwebsocket)(streamUrl);
ws.onerror = function () {
console.log('Connection Error');
};
ws.onopen = function () {
console.log('W3C WebSocket Client Connected');
};
ws.onclose = function () {
console.log('W3C WebSocket Client Disconnected');
};
ws.onmessage = function (e) {
// Occasionally, the Direct Line service sends an empty message as a liveness ping
// Ignore these messages
this.viewer = new W3CWebSocket(`${URL}/viewer`);
this.viewer.onopen = () =>
this.setState(setReadyState('viewer', this.viewer));
this.viewer.onclose = () => {
if (this.isComponentUnmount) return;
this.setState(setReadyState('viewer', this.viewer));
};
this.viewer.onmessage = payload => {
const data = JSON.parse(payload.data);
onMessage(this.props)(data); // Remind: Handle receieve messages.
};
this.viewer.onerror = error => console.info('viewer onerror', error);
}
if (!this.sender || this.sender.readyState >= CLOSING) {
this.sender = new W3CWebSocket(`${URL}`);
this.sender.onopen = () => {
this.setState({ send: this.sender.send.bind(this.sender) });
this.setState(setReadyState('sender', this.sender));
};
this.viewer.onclose = () => {
if (this.isComponentUnmount) return;
this.setState(setReadyState('sender', this.sender));
};
this.sender.onmessage = e => console.info('sender onmessage', e.data);
this.sender.onerror = error => console.info('sender onerror', error);
}
};
options.httpServer.on('upgrade', function(req, socket, head) {
if (typeof req.headers['sec-websocket-version'] !== 'undefined') {
// WebSocket hybi-08/-09/-10 connection (WebSocket-Node)
wsRequest = new WebSocketRequest(socket, req, wsServerConfig);
try {
wsRequest.readHandshake();
} catch (e) {
wsRequest.reject(
e.httpCode ? e.httpCode : 400,
e.message,
e.headers
);
return;
}
wsRequest.once('requestAccepted', function(connection) {
wsRequest.handleRequestAccepted(connection);
});
self.emit('request', wsRequest);
} else {
httpServer.on('upgrade', function(req, socket, head) {
if (typeof req.headers['sec-websocket-version'] !== 'undefined') {
// WebSocket hybi-08/-09/-10 connection (WebSocket-Node)
var wsRequest = new WebSocketRequest(socket, req, wsServerConfig);
try {
wsRequest.readHandshake();
var wsConnection = wsRequest.accept(wsRequest.requestedProtocols[0], wsRequest.origin);
handleConnection(wsConnection);
}
catch(e) {
console.log("WebSocket Request unsupported by WebSocket-Node: " + e.toString());
return;
}
} else {
// WebSocket hixie-75/-76/hybi-00 connection (node-websocket-server)
if (req.method === 'GET' &&
(req.headers.upgrade && req.headers.connection) &&
req.headers.upgrade.toLowerCase() === 'websocket' &&
next();
}));
});
});
app.listen(cfg.port, '0.0.0.0');
var wsServer = new WebSocketServer({
httpServer: app,
// Firefox 7 alpha has a bug that drops the
// connection on large fragmented messages
fragmentOutgoingMessages: false
});
var router = new WebSocketRouter();
router.attachServer(wsServer);
function originIsAllowed(url) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
/*
wsServer.on('request', function(request) {
var url = request.httpRequest.url;
if (!originIsAllowed(url)) {
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}