Introduction
I have cloned the project from this git link here
App is running on localhost fine.I am willing to deploy this demo project on windows server where it will run on https://localhost:8443. I have no idea how to deploy this specific demo project, although i have successfully deployed another simple node application on iis.
What can be causing problem, i think from script server.js
var path = require('path');
var url = require('url');
var express = require('express');
var minimist = require('minimist');
var ws = require('ws');
var kurento = require('kurento-client');
var fs = require('fs');
var https = require('https');
var argv = minimist(process.argv.slice(2), {
default: {
as_uri: 'https://localhost:8443/',
ws_uri: 'ws://93.104.213.28:8888/kurento'
}
});
var options =
{
key: fs.readFileSync('keys/server.key'),
cert: fs.readFileSync('keys/server.crt')
};
var app = express();
/*
* Definition of global variables.
*/
var idCounter = 0;
var candidatesQueue = {};
var kurentoClient = null;
var presenter = null;
var viewers = [];
var noPresenterMessage = 'No active presenter. Try again later...';
/*
* Server startup
*/
var asUrl = url.parse(argv.as_uri);
var port = asUrl.port;
var server = https.createServer(options, app).listen(port, function() {
console.log('Kurento Tutorial started');
console.log('Open ' + url.format(asUrl) + ' with a WebRTC capable browser');
});
var wss = new ws.Server({
server : server,
path : '/one2many'
}); .....other code
I have been trying this for 2 days but no luck.Any expert might help.
Thanks for your time.
Related
at the moment I have an app.js file and a server.js file. The server runs fine when I run 'node app.js' in CMD but I'm trying to put everything in the server.js file.
App.js:
var Server = require('./server.js').Server;
var server = new Server();
server.initialise(8080);
Server.js:
var express = require('express');
var http = require('http');
var events = require('events');
var io = require('socket.io');
var app = express();
exports.Server = Server = function() {
this.userId = 1;
};
Server.prototype.initialise = function(port) {
this.server = http.createServer(app);
app.use(express.static('public'));
this.server.listen(port);
this.startSockets();
this.em = new events();
console.log('Server running on port: ' + port);
};
So I've tried moving the last 2 lines of app.js to the server but I'm getting the error that Server isnt a constructer. I've tried
var Server = this;
I've also tried
this.initialise(8080);
Nothing seems to work
i want to send a websocket, using express-ws out from a different controller, not by route and I have the following code in the server.js:
var SocketController = require('./routes/ws.routes');
var app = express();
var server = require('http').createServer(app);
var expressWs = require('express-ws')(app);
app.ws('/', SocketController.socketFunction);
the SocketController looks like that:
exports.socketFunction = function (ws, req) {
ws.on('message', function(msg) {
console.log(msg);
ws.send("hello");
});
}
Is it possible to call the
ws.send()
event from another controller? How do i get the "ws" object?
thanks!
You will have to store your sockets in memory. To access stored sockets from different modules, you can store references for these sockets in a separate module.
For example, you can create a module socketCollection that stores all the active sockets.
socketCollection.js:
exports.socketCollection = [];
You can import this module where you define your web socket server:
var socketCollection = require('./socketCollection');
var SocketController = require('./routes/ws.routes');
var app = express();
var server = require('http').createServer(app);
var expressWs = require('express-ws')(app);
expressWs.getWss().on('connection', function(ws) {
socketCollection.push({
id: 'someRandomSocketId',
socket: ws,
});
});
app.ws('/', SocketController.socketFunction);
Now every time new client connects to the server, it's reference will be saved to 'socketCollection'
You can access these clients from any module by importing this array
var socketCollection = require('./socketCollection');
var ws = findSocket('someRandomSocketId', socketCollection);
var findSocket = function(id, socketCollection) {
var result = socketCollection.filter(function(x){return x.id == id;} );
return result ? result[0].socket : null;
};
I have a Nodejs Server.js code :
first Concept :
var http = require('http');
var express = require('express');
var app = express();
var path = require('path');
var conn= http.createServer(app).listen(3000, function () {
console.log("server Running at Port 3000");
});
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({server: conn});
and i have a index.html code with java script :
<html>
<body>
<script src="myscript.js"></script>
</body>
</html>
inside myscript.js i have :
var connection = new WebSocket('ws://localhost:3000');
This is working fine when i open http://localhost:3000 on browser .
second Concept :
my server.js :
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({ port: 3000}) ;
wss.on('connection', function (connection) {
});
wss.on('listening', function () {
console.log("Server started...");
});
and HTML and client java script is similar as above .
This is not working when i open http://localhost:3000 on browser . why ? i want to clarify my doubt . Why the first method working and second is not working ?
To specifically answer your question: why web socket behave differently on nodejs? the answer is: It shouldn't. In the second version of your code you are not serving any HTML or JS files to the client on the port 3000 so the browser can't download any HTML.
If you want it to work as expected then you need to serve some HTML and JS files to the browser that visits http://localhost:3000/ or otherwise it will not be able to connect.
I wrote some example code - both server-side and client-side - on how to use WebSocket to do exactly what you are trying to do here. It's available on GitHub and I originally wrote it for this answer: Differences between socket.io and websockets.
The relevant parts of the source code for your question here are:
WebSocket Server
WebSocket server example using Express.js:
var path = require('path');
var app = require('express')();
var ws = require('express-ws')(app);
app.get('/', (req, res) => {
console.error('express connection');
res.sendFile(path.join(__dirname, 'ws.html'));
});
app.ws('/', (s, req) => {
console.error('websocket connection');
for (var t = 0; t < 3; t++)
setTimeout(() => s.send('message from server', ()=>{}), 1000*t);
});
app.listen(3001, () => console.error('listening on http://localhost:3001/'));
console.error('websocket example');
Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.js
WebSocket Client
WebSocket client example using vanilla JavaScript:
var l = document.getElementById('l');
var log = function (m) {
var i = document.createElement('li');
i.innerText = new Date().toISOString()+' '+m;
l.appendChild(i);
}
log('opening websocket connection');
var s = new WebSocket('ws://'+window.location.host+'/');
s.addEventListener('error', function (m) { log("error"); });
s.addEventListener('open', function (m) { log("websocket connection open"); });
s.addEventListener('message', function (m) { log(m.data); });
Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.html
Instead of debugging a code that it not working, sometimes it's better to start from something that works and go from there. Take a look at how it all works and feel free to change it and use it in your projects - it's released under MIT license.
I am creating a game using socket io. A player connects like this:
var playerName = document.getElementById("name").value;
socket.emit('setup player', {
name : playerName
});
Then on the server, the player is setup and his information is sent back to the client:
function onSetupPlayer(data) {
...
var newPlayer = new Player(x, y, color, data.name,
this.id, scale);
socket.emit('setup game', {
localPlayer : newPlayer
});
...
sockets[this.id] = socket;
}
The following call:
socket.emit('setup game', {
localPlayer : newPlayer
});
Should send the setup data only back to the client that requested the setup to be done originally. However the setup call gets send to everyone in the lobby.
Could this have anything to do with the fact that I am using localhost to test it? I am also testing it on the same machine by using different tabs. If this is what is causing the issue, is there a way to resolve it? Since this is pretty annoying when testing my game.
EDIT:
Initialization:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var socket = require('socket.io')(http);
var path = require('path');
var io = require('socket.io')(80);
...
var setEventHandlers = function() {
socket.sockets.on("connection", onSocketConnection);
};
Listening for connection:
function onSocketConnection(client) {
...
client.on("setup player", onSetupPlayer);
...
};
And on the client side I have this:
var setEventHandlers = function() {
socket.on("setup game", onSetupGame);
...
}
socket.emit send event to everyone excepts this. To send data back to this user try
io.to(socket).emit()
I am trying to install protractor in my Mac. The installation is done via command line but one of the scripts is failing due to connectivity problems. The main problem is that I am behind a corporate proxy server.
I set the proxy server in my console and npm is also configured with the correct proxy settings.
The script that fails is here
and it contains the following
#!/usr/bin/env node
var fs = require('fs');
var os = require('os');
var url = require('url');
var http = require('http');
var AdmZip = require('adm-zip')
// Download the Selenium Standalone jar and the ChromeDriver binary to
// ./selenium/
// Thanks to http://www.hacksparrow.com/using-node-js-to-download-files.html
// for the outline of this code.
var SELENIUM_URL =
'http://selenium.googlecode.com/files/selenium-server-standalone-2.35.0.jar';
var CHROMEDRIVER_URL_MAC =
'https://chromedriver.googlecode.com/files/chromedriver_mac32_2.2.zip';
var CHROMEDRIVER_URL_LINUX32 =
'https://chromedriver.googlecode.com/files/chromedriver_linux32_2.2.zip';
var CHROMEDRIVER_URL_LINUX64 =
'https://chromedriver.googlecode.com/files/chromedriver_linux64_2.2.zip';
var CHROMEDRIVER_URL_WINDOWS =
'https://chromedriver.googlecode.com/files/chromedriver_win32_2.2.zip';
var DOWNLOAD_DIR = './selenium/';
var START_SCRIPT_FILENAME = DOWNLOAD_DIR + 'start';
var chromedriver_url = '';
var start_script = 'java -jar selenium/selenium-server-standalone-2.35.0.jar';
if (!fs.existsSync(DOWNLOAD_DIR) || !fs.statSync(DOWNLOAD_DIR).isDirectory()) {
fs.mkdirSync(DOWNLOAD_DIR);
}
console.log(
'When finished, start the Selenium Standalone Server with ./selenium/start \n');
// Function to download file using HTTP.get
var download_file_httpget = function(file_url, callback) {
console.log('downloading ' + file_url + '...');
var options = {
host: url.parse(file_url).host,
port: 80,
path: url.parse(file_url).pathname
};
var file_name = url.parse(file_url).pathname.split('/').pop();
var file_path = DOWNLOAD_DIR + file_name;
var file = fs.createWriteStream(file_path);
http.get(options, function(res) {
res.on('data', function(data) {
file.write(data);
}).on('end', function() {
file.end(function() {
console.log(file_name + ' downloaded to ' + file_path);
if (callback) {
callback(file_path);
}
});
});
});
};
download_file_httpget(SELENIUM_URL);
if (!(process.argv[2] == '--nocd')) {
if (os.type() == 'Darwin') {
chromedriver_url = CHROMEDRIVER_URL_MAC;
} else if (os.type() == 'Linux') {
if (os.arch() == 'x64') {
chromedriver_url = CHROMEDRIVER_URL_LINUX64;
} else {
chromedriver_url = CHROMEDRIVER_URL_LINUX32;
}
} else if (os.type() == 'Windows_NT') {
chromedriver_url = CHROMEDRIVER_URL_WINDOWS;
}
var chromedriver_zip = chromedriver_url.split('/').pop();
start_script += ' -Dwebdriver.chrome.driver=./selenium/chromedriver';
download_file_httpget(chromedriver_url, function(file_name) {
var zip = new AdmZip(file_name);
zip.extractAllTo(DOWNLOAD_DIR);
if (os.type() != 'Windows_NT') {
fs.chmod(DOWNLOAD_DIR + 'chromedriver', 0755);
}
});
}
var start_script_file = fs.createWriteStream(START_SCRIPT_FILENAME);
start_script_file.write(start_script);
start_script_file.end(function() {
fs.chmod(START_SCRIPT_FILENAME, 0755);
});
How can we modify this script in order to resolve the connectivity issue?
In download_file_httpget, you're calling http.get(...). That makes a direct connection to the target server.
Configuring a proxy in npm only affects npm. Node's http module has no concept of proxy servers.
If you need to make a request through a proxy, consider using the request module, which does support proxies.