I'm trying to build a web chat application and want to connect my client to the socket.io server with https.
Seems like everything's fine, but the client is not connecting after all..
Server Code:
var app = require('express')();
var fs = require('fs');
var options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
};
var server = require('https').createServer(options, app).listen(3000,function(){
console.log("Https server started on port 3000");
});
var io = require('socket.io').listen(server);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log("Client connected");
/*....*/
});
Client code to connect to server:
$(function($){
var socket = io.connect('https://localhost:3000', {secure: true});
.....
});
It kind of doesn't run the code inside of $(function($)..
When I make it a http server it works just fine..
Simply
var socket = io.connect('/', {secure: true});
EDIT: By default socket.io will try to establish a connection on the same host as webserver hosts web content, so no need to specifying host/protocol/port. The / states to connect to default namespace.
I solved the problem..
So for http it was enough if you begin your script on the client with
$(function(){
....
});
But it wouldn't work with https.
I changed it to
jQuery(function($){
....
})(jQuery);
Pretty odd but it worked for me.
Related
I'm trying to connect two node.js servers via websocket using the ws package. Here is some code:
Client server:
var socket = new WebSocket("wss://localhost:9000");
socket.addEventListener('open', function (event) {
console.log("websocket connected");
})
socket.addEventListener('message', function (event) {
console.log("message from backend server: ", event.data);
})
Backend server:
var https = require('https');
var httpsServer = https.createServer(credentials, app);
const WebSocket = require('ws');
const wss = new WebSocket.Server({ server:httpsServer });
wss.on('connection', function (ws) {
console.log("websocket connnected");
})
httpsServer.listen(9000, function () {
console.log(`server started on port 9000 via https`);
});
When I run this code, a get an error message on the command prompt that says "Error: certificate has expired". I am using a self-signed ssl certificate, which works perfectly fine for a websocket between a node.js server and the browser so I'm not convinced there's anything wrong with the certificate. I've seen examples of how to make this work using socket.io and socket.io-client, but how can I make it work using the ws package?
This is a problem with the ssl certificate. For some reason, going from browser to node.js server using a self-signed ssl certificate is fine, but going from node.js server to node.js using a self-signed ssl certificate is not.
I created a brand new ssl certificate and then in the client server, instead of:
var socket = new WebSocket("wss://localhost:9000");
.. I now have:
var socket = new WebSocket("wss://localhost:9000", {
rejectUnauthorized: false
});
..and it works.
I'm trying to set up a socket.io connection on Cloud Foundry via IBM Toolchains. I've gone through the docs and have been trying to get socket.io to connect to port 4443. I'm kind of new to this so would appreciate if you could provide some pointers on how to set up socket.io on the CF env as I still struggle to digest parts of the documentation. Code can be found below.
//---------------------------
// app.js
//---------------------------
// Start the app on cloud foundry
var express = require('express');
var app = express();
var cfenv = require('cfenv');
var appEnv = cfenv.getAppEnv();
app.use(express.static(__dirname + '/public'));
app.listen(appEnv.port, '0.0.0.0', function() {
console.log("Server is starting on " + appEnv.url);
});
// Connect socket.io
var server = require('http').Server(app);
var io = require('socket.io')(server);
var cookieParser = require('cookie-parser');
app.get('/', function (req, res) {
res.sendFile(__dirname + 'public/index.html');
});
io.on('connection', function (socket) {
console.log('a user connected');
});
var port = 4443; // Cloud Foundry assigned port for TCP/WebSocket communications
server.listen(port, function() {
console.log('listening on ', port);
});
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect("https://0.0.0.0:4443");
</script>
My understanding after going through the socket.io docs is that the IP provided should be the location.hostname which I believe to be 0.0.0.0 in this case as it refers to the IP which the express instance for the app is listening on. Not too sure about this though.
By changing it to below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.slim.js"></script>
<script> var socket = io(); </script>
The error changes to a 404 error with the following error being repeated: "https://realtimetrafficanalysisaks.mybluemix.net/socket.io/?EIO=3&transport=polling&t=". I've checked regarding the app and server settings but can't seem to pinpoint the error
Thanks in advance!
I didn't manage to sort this out with socket.io due to the port issue but I was able to get it running using the express-ws package
I'm trying to use a simple post request on a route on top of a mongo DB.
my js file (I combined the router with the app) looks like:
var express = require('express');
var app = express();
var router = express.Router();
app.use(express.static('public'));
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server;
var url = 'mongodb://localhost:27017/test';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to', url);
//Close connection
//db.close();
}});
router.post('/', function(req, res){
res.send('Got a POST request');
});
app.listen(27017,function(){
console.log("Server started successfully at Port 27017!");
});
on my html file I simple have a section like this (yes, my post request doesn't do much for now):
$.ajax({
method: "POST",
url: "localhost:27017/test/",
});
I can't seem to get it to work, my console keeps throwing: "[Error] Failed to load resource: unsupported URL (localhost:27017/test/, line 0)"
at me, and when I try to browse directly to the url via my browser I'm getting a "Cannot GET /test/" message.
What am I doing wrong?
Sharing what worked for me in the end:
1. Changed the app to listen to 3000 (or any other port that my DB server wasn't listening to). Thanks TomG.
2.changed router.post to app.post (you can use expressing routing but I had a mistake there).
I'm new to socket.io and have been able to get many examples from different tutorials working correctly on my localhost. Now I need help getting it to work on my website. I've been browsing support forms for days with no luck. Any help would be appreciated. Here is what I've done so far...
I exported the code (which was working on my localhost) to my web server (hosted by https://ifastnet.com/) using FileZilla FTP Client and did the same "npm init", "npm install express --save", "npm install socket.io --save", "node app.js" procedure on putty SSH that I used on my CMD when I was able to get it to work on my localhost.
When I go to my website I keep getting "net::ERR_CONNECTION_RESET" in the browser console (google chrome) when I use
var socket = io.connect('http://31.22.4.6:1122');
on the client side.
I get "404 (Not Found)" in the browser console when I use
var socket = io();
I've tried many solutions with no luck
My code is below. Thanks in advance for the help.
server
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen();
// server.listen(1122, "31.22.4.6");
app.get('/', function(req, res) {
res.sendfile(__dirname + '/client/index.html');
});
console.log("server started");
io.on('connection', function(socket) {
console.log("connection made");
socket.emit('news', {
hello: 'world'
});
socket.on('my other event', function(data) {
console.log(data);
});
});
client
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
// var socket = io.connect('http://localhost');
// var socket = io.connect('http://31.22.4.6:1122');
var socket = io();
// var socket = io.connect();
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
Are you using https://ifastnet.com. It doesn't appear that you have access to run node on their servers nor do you have access to serve content on port 1122.
You'll need a service that provides you with ssh, something like Amazon. They have a free-tier service for you to try out a Ubuntu virtual machine for a few months if you want to try before you buy.
I have the current setup:
Nodejs Proxy (running http-reverse-proxy) running on port 80.
Rails server running on port 3000
Nodejs web server running on port 8888
So any request starting with /nodejs/ will be redirected to nodejs web server on 8888.
Anything else will be redirected to the rails server on port 3000.
Currently Socket.io requires a connection url for io.connect.
Note that /nodejs/socket.io/socket.io.js is valid and returns the required socket.io client js library.
However, I am not able to specify connection_url to /nodejs/ on my server.
I have tried http://myapp.com/nodejs and other variants but I am still getting a 404 error with the following url http://myapp/socket.io/1/?t=1331851089106
Is it possible to tell io.connect to prefix each connection url with /nodejs/ ?
As of Socket.io version 1, resource has been replaced by path. Use :
var socket = io('http://localhost', {path: '/nodejs/socket.io'});
See: http://blog.seafuj.com/migrating-to-socketio-1-0
you can specify resource like this:
var socket = io.connect('http://localhost', {resource: 'nodejs'});
by default resource = "socket.io"
If you are using express with nodejs:
Server side:
var io = require('socket.io')(server, {path: '/octagon/socket.io'});
then
io.on('connection', function(socket) {
console.log('a user connected, id ' + socket.id);
socket.on('disconnect', function() {
console.log('a user disconnected, id ' + socket.id);
})
})
socket.on('publish message ' + clientId, function(msg) {
console.log('got message')
})
Client side:
var socket = io('https://dev.octagon.com:8443', {path: '/octagon/socket.io'})
then
socket.emit('publish message ' + clientId, msg)
I use below approach to achieve this goal:
client side:
var socket = io.connect('http://localhost:8183/?clientId='+clientId,{"force new connection":true});
server side:
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket) {
console.log("url"+socket.handshake.url);
clientId=socket.handshake.query.clientId;
console.log("connected clientId:"+clientId);
});
reference:https://github.com/LearnBoost/socket.io/wiki/Authorizing#global-authorization
If you are serving your app with express, then maybe you can check this out. Remember express uses http to serve your application.
const express = require('express'),
http = require('http'),
socketIo = require('socket.io'),
app = express()
var server = http.createServer(app);
var io = socketIo(server);
io.on('connection', (socket)=>{
// run your code here
})
server.listen(process.env.PORT, ()=> {
console.log('chat-app inintated succesfully')
})