I want my sockets to communicate securely. I think I'm requesting communication over https. So why is the secure flag always false? I've tried a bunch of different flag settings with no effect so far.
Sample site developed on glitch.com here: https://glitch.com/edit/#!/sponge-tablecloth.
Landing page is here: https://sponge-tablecloth.glitch.me/
Client page code:
<div id="div"></div>
<script src="/socket.io/socket.io.js"></script>
<script>
socket = io("https://sponge-tablecloth.glitch.me/");
socket.on('message', function(message) { div.innerHTML += message + "<br>"; });
</script>
Node.js server code:
var express = require('express');
var app = express();
let http = require('http').Server(app);
app.use(express.static('public'));
app.get("/", function (request, response) {
response.sendFile(__dirname + '/views/index.html');
});
let io = require('socket.io')(http);
io.on('connection', function(socket) {
console.log("checking connection, secure: " + socket.handshake.secure);
io.emit('message', "checking a connection, secure: " + socket.handshake.secure);
});
let listener = http.listen(process.env.PORT, function(){
console.log('Your app is listening on port ' + listener.address().port);
});
Problem is most likely that a reverse proxy is terminating TLS before proxying the requests to your application. It is common to have a setup that looks like this:
User -[HTTPS]-> Nginx(terminate TLS) -[HTTP]-> Application
This means that your application thinks that the transport was always insecure, while in fact it's just been terminated by the proxy (in this case Nginx). Glitch.io likely does this exact thing since your application is only offering insecure HTTP connections.
If you want end-to-end encryption you need to use the https package from stdlib instead of the http package, and setup certificates.
Related
I’m a long term programmer, but haven’t used nodejs much in my code. Now I need to use it in my current code and I’ve ran into a problem that I can’t seem to figure out myself, I have googled a lot but nothing seem to fix it.
I am trying to get my website to connect to the nodejs server running on same host.
If I visit the url in my browser, it works fine (http://localhost:6857/socket.io/?EIO=4&transport=polling) and I see this respond
0{"sid":"s_v860SbNO4toknPAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}
But when I try to connect thru the website, I just get
GET http://localhost:6857/socket.io/?EIO=3&transport=polling&t=N_gL_HZ net::ERR_CONNECTION_REFUSED
Can someone guide my in the right direction for how to fix this, so I can begin using nodejs inside my website?
This is my server.js
// use express
var express = require("express");
// create instance of express
var app = express();
// use http with instance of express
var http = require("http").createServer(app);
// start the server
var port = 6857;
http.listen(port, '0.0.0.0', function () {
console.log("Listening to port " + port);
});
// create socket instance with http
var io = require("socket.io")(http);
// add listener for new connection
io.on("connection", function (socket) {
// this is socket for each user
console.log("User connected", socket.id);
});
io.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
And this is my JS code inside my website
<script>
var server = "http://localhost:6857/";
var io = io(server);
</script>
Socket IO requires you to enable CORS explicitly - Thus why you get the error stated above.
To enable CORS, please see the following link
I have a NodeWebkit client which connects to a nodejs server using the socket.io library (JavaScript).
The client launches the connect procedure on the application start but the server does not acknoledge any connections... Though the client's socket has the connected attribute to "true".
You should know that I am using socketio-jwt to authentificate the connection.
Github: https://github.com/auth0/socketio-jwt
I know that the connection does work in a way because if I add :
io.sockets.on('connection', function(){console.log("hello");})
It prints hello !
So it seems that event though the connection is somehow made it doesn't want to do the auth part with the library, resulting in... Well... Nothing.
But that's not all !!
Because if I reboot the app (not the server) then the auth works most of the time ! It acts like a race condition... But I dont see how it could possibly be one... Every line of code is geting executed appart of the success callback of authentification.
I tried connecting to a remote server and on my localhost.
I also tried with an other library of socket auth but I've got the same probleme.
This is the server code:
var session = require('express-session');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var socketioJwt = require('socketio-jwt');
io.sockets.on('connection', socketioJwt.authorize({
secret: 'some secret',
timeout: 15000 // 15 seconds to send the authentication message
})).on('authenticated', function (socket) {
console.log('[Info]: A user connected to socket = ', socket.decoded_token);
});
});
http.listen(5000, function () {
console.log('listening on *:5000');
});
And now the client code:
this.socket = io.connect('http://' + that.hostName +':' + that.port);
var token = jwt.sign({email: "someEail", pwd: "somePwd"}, fromServerSecret);
this.socket.on('connect', function () {
that.socket.emit('authenticate', {token: token}) //send the jwt
.on('authenticated', function () {
console.log("[Info]: Socket login successfull");
})
.on('unauthorized', function (msg) {
console.log("[Warning]: Socket unauthorized: " + JSON.stringify(msg.data));
throw new Error(msg.data.type);
});
});
The server side log "A user connected to socket" is never shown.
If you have an idear ! Thanks for your time.
Why is there a 'that' on socket.emit (client)? I think you should handle it within the same instance of socket.io - using same 'this' as above
I am trying to impliment websocket chat in mvc5 application using node.js and websocket for this I am using URL rewriter.
I am created a node server with following code.
var app = require('express')();
//creating http server
var server = require('http').createServer(app);
//add webrtc.io functionality to http server
var webRTC = require('webrtc.io').listen(server);
//port which is allocated dynamically by visual studeo IIS/iisexpress server, which of string formate.
var port = process.env.PORT;
//let the server in listen mode for the port id assigned by IIS server.
server.listen(port);
//this is for testing purpose, which returns the string, for the specified url request
app.get('/test/websocketcon', function (req, res)
{
res.end("working");
});
If i am trying to to access the https://localhost:44300/test/websocketcon. I am getting response as "working". But If I am trying to create new websocket I am getting error as
WebSocket connection to 'wss://localhost:44300/Home/websocketcon'
failed: Error during WebSocket handshake: Unexpected response code:
404
Code I have tried to create new websocket
var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://';
var address = protocol + window.location.host + window.location.pathname + "/websocketcon";
var createdwebsocket = new WebSocket(address );
your express route/server listens on for http requests, not wss. check this out: https://www.npmjs.com/package/express-ws
To explain in depth:
With the following lines of code, you have created a http server:
var app = require('express')();
var server = require('http').createServer(app);
http is what protocol you use when when you connect to http://yoursite.com. However, you are trying to connect a websocket to your server. to do this, you need to add a websocket listener and route to your server. This is because websockets don't work over the http protocol, they work over the websocket protocol.
To make a websocket server, checkout the link/module I have provided above. You should have a server which listens for both http requests and websocket requests. To make your current code work with websockets, what you need to do is make the following changes:
var app = require('express')();
var server = require('http').createServer(app);
// now add the express websocket functionality
var expressWs = require('express-ws')(app);
.
.
.
app.ws('/test/websocketcon', function (ws, req)
{
ws.send("Working!");
ws.on('message', function(msg) {
ws.send(msg);
});
});
I currently have a working app utilizing passport.js authentication and socket.io for web sockets. It works fine via the http protocol, but as soon as I tell socket.io to listen to the https server, deserializeUser() fires for every connect event and no connection is made, no socket.io middleware is called.
HTTP (works):
var server = http.createServer(app).listen(port) //3000;
var io = require('socket.io').listen(server);
HTTPS (fails):
var httpsServer = https.createServer(sslOptions, app).listen(httpsPort)//8443;
//also attempted without any additional options supplied to io.listen()
var io = require('socket.io').listen(httpsServer, {
"log level": 3,
"match origin protocol" : true,
"transports" : ['websocket']
});
The client side:
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
Socket.io middleware that should be responding (again, same middleware works when http server is supplied to io.listen()):
module.exports = function(app, io){
io.on('connection', function(socket){
console.log('base connection');
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
socket.on('disconnect', function(){
console.log('disconnect');
});
});
};
Do I have to specify protocol in the client somehow? I assume the io manager should use the url protocol. I also assumed passing "match origin protocol" : true as an option should use https. Any advice or assistance is appreciated.
EDIT:
The client throws a network error, net::ERR_INSECURE_RESPONSE
I'm relatively new to node.js and it's addons, so this is probably a beginnersquestion.
I'm trying to get a simple HTML page on a webserver connect to a different server running node.js with websocket.io.
My code looks like this:
Client
<script src="socket.io/socket.io.js"></script>
<script>
// Create SocketIO instance, connect
var socket = new io.Socket();
socket.connect('http://127.0.0.1:8080');
// Add a connect listener
socket.on('connect',function() {
console.log('Client has connected to the server!');
});
// Add a connect listener
socket.on('message',function(data) {
console.log('Received a message from the server!',data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
console.log('The client has disconnected!');
});
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
};
</script>
Serverside
// Require HTTP module (to start server) and Socket.IO
var http = require('http');
var io = require('socket.io');
var port = 8080;
// Start the server at port 8080
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(port);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
// Add a connect listener
socket.on('connection', function(client){
console.log('Connection to client established');
// Success! Now listen to messages to be received
client.on('message',function(event){
console.log('Received message from client!',event);
});
client.on('disconnect',function(){
clearInterval(interval);
console.log('Server has disconnected');
});
});
console.log('Server running at http://127.0.0.1:' + port + '/');
Starting up the server works fine and running http://localhost:8080 in my browser also works, returning 'Hello Socket Lover' as expected. But I want to make a different page talk to the sockets, not run one from node.js.
But when I run it, nothing happens and the Chrome console returns:
Failed to load resource http://undefined/socket.io/1/?t=1333119551736
Failed to load resource http://undefined/socket.io/1/?t=1333119551735
I've been at this all day. Any help?
Have you tried loading the socket.io script not from a relative URL?
You're using:
<script src="socket.io/socket.io.js"></script>
And:
socket.connect('http://127.0.0.1:8080');
You should try:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
And:
socket.connect('http://localhost:8080');
Switch localhost:8080 with whatever fits your current setup.
Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).
You need to make sure that you add forward slash before your link to socket.io:
<script src="/socket.io/socket.io.js"></script>
Then in the view/controller just do:
var socket = io.connect()
That should solve your problem.
Instead of:
var socket = new io.Socket();
Try:
const socket = io();
Also add a server file:
const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
app.use(express.static(__dirname + '/public'));
const io = require('socket.io')(server);
const PORT = 5000;
server.listen(PORT, () => {
console.log(`Server is Listening On Port ${PORT}`);
});