Socket.io serve 404 for non-socket.io urls - node.js

We have some kind of chat app using nodejs and socket.io as server. Client is just a regular PHP based app. It is working quite well.
However, we would like to serve 404 errors for URLs not associated with the socket.io app, like the base url, favicon.ico and the rest of the urls.
For example, the server is at:
https://awesome-messenger.com
and the usual socket.io url is at:
https://awesome-messenger.com/socket.io/*
We would like to throw 404 to anything else not handled by socket.io.
Current setup:
nodejs 6.x
socket.io latest
Sample code (messenger.js):
var app = require('http').createServer()
var io = require('socket.io')(app);
app.listen(4040);
io.on('connection', function (socket) {
socket.on('joinRoom', function(data){
socket.join(data.room);
});
// Other codes here...
});
Started by:
node /path/to/messenger.js
Thanks!

We used express + socket.io instead to serve a custom homepage and throw 404 errors on non-socket.io urls. I got the idea from here: http://socket.io/get-started/chat/
var app = require('express')(),
http = require('http').Server(app),
io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.on('joinRoom', function(data){
socket.join(data.room);
});
// Other codes
});
http.listen(4040, function () {
console.log('Listening on *:4040');
});
So if we access something like: /favicon.ico or /foo/bar, it will throw a simple 404 error.

Related

Why do I need to add "require("http")" when I already have express?

I am trying to follow this tutorial on creating a simple chat application using socket.io. I am at the part of the tutorial where I have to insert all of the code below into a js file and initiate it. I just don't understand why the 2nd of code exist, I heard that express can do a lot more than http. Instead of using the "http.listen" code, can't "app.listen" be used and "app" passed to "io" instead?
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Why do I need to add “require(”http“)” when I already have express?
You don't have to manually load the http module yourself. You use express to create an http server for you (it will load the http module for you) and integrate it with socket.io without manually loading the htttp module like this:
const app = require('express')();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
const server = app.listen(3000, function(){
console.log('listening on *:3000');
});
const io = require('socket.io')(server);
io.on('connection', function(socket){
console.log('a user connected');
});
Internally, app.listen() loads the http module for you, creates a server and then starts it, returning the server object which you can then use with socket.io.
Inside of express, this is the code for app.listen():
const http = require('http');
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
So, somebody had to load the http module. If you use app.listen(), the express will do it for you.
You are right. Express is a framework that sits on top of the nodejs application and provides a much easier,provided more middleware to handle routes, session and cookies and more efficient way to create server as such
var express = require('express');
var app = express();
app.listen(3000);
In this example, for the purpose of creating a socket between different channels, you have to use HTTP to indicate that the socket is used to handle HTTP requests/responses. You simply can't pass an entire express application to io.

Fail to use socket.io not found

My structure
game.js
node_modules\
public\
|index.html
|js\main.js
game.js is nodejs server and in plubic folder is client side
In index.html I have
<script src="/socket.io/socket.io.js"></script>
But when i run in web browser it say
GET http://localhost:1000/socket.io/socket.io.js 404
(index):3 Uncaught ReferenceError: io is not defined
at (index):3
But when i download socket.io.js and make like this
game.js
node_modules\
public\
|index.html
|js\main.js
|socket.io\socket.io.js
And run again it localhost:1000 say
localhost:1000/socket.io/?EIO=3&transport=polling&t=Lg5U91n 404 (Not Found)
what is mistake. I run in window. How to fix that thank.
You will need to include socketio-client on the client side via the script tag. That will allow IO to be defined.
<script>
var socket = io.connect('http://localhost:1000');
socket.on('connect', function(data) {
//Do Something here
});
</script>
You will also need to make sure on your backed (the server that socketio is connecting to) has socketio properly defined and is being used in the HTTP server. An example would be:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res,next) {
res.sendFile(__dirname + '/index.html');
});
server.listen(1000);
io.on('connection', function(client) {
console.log('Client connected...');
//socket code here
});
Its very hard for us to help you without any code sample of what you are working with. The example provided is a very BASIC way of getting socketio up and running.
Checkout the socketio client github that has a quick and simple demonstration of what to do as well:
Socket.io Client Github

Socket.io doesn't initialize and doesn't connect to the node server on shared hosting

I have installed node.js on my shared hosting with GoDaddy and can run node apps.
I don't exactly know where the problem is, but here's what's going on. I run the server, and it starts listening on a port (I tried a range from 49000 to 56000).
But when the client tries to connect, i.e. access '/' on the server, the node is silent, therefore it doesn't receive any connection requests. So that kind of narrows it down to socket.io.
In the console within a few seconds it spits out this:
socket.io-1.4.5.js:1 GET http://website.com:55872/socket.io/?EIO=3&transport=polling&t=LQRdEP9 net::ERR_CONNECTION_TIMED_OUT
I have tried to source socket.io from the cdn as well as my own directory - nothing.
This is what the server looks like:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
//------------- GLOBAL VARIABLES ---------------
SERVER_PORT = 55872;
connections = [];
//----------------------------------------------
server.listen(SERVER_PORT, "127.0.0.1");
console.log('................................................');
console.log('=> Server is listening on port: ' + SERVER_PORT);
console.log('................................................');
app.get('/', function(req, res){
console.log('=> Loading index.html!');
res.sendFile(__dirname + '/index.html');
});
// ----------- MIDDLEWARE ----------------------
// ----------- CONNECTIONS ---------------------
io.sockets.on('connection', function(socket){
connections.push(socket);
console.log('=> Client connected! Total connected: %s', connections.length);
// Disconnect socket
socket.on('disconnect', function(data){
connections.splice(connections.indexOf(socket), 1);
console.log('=> Client disconnected! Total connected: %s', connections.length);
});
Client:
$(function(){
//--------- SOCKET INIT --------------
var socket = io.connect('http://website.com:55872/');
});
Is the issue with socket.io or the node, or me...?
GoDaddy does not currently support running node.js servers on shared hosting. You would need a VPS account. GoDaddy did buy Nodejitsu so presumably they will be expanding their node.js offerings, but as of this moment you can't run node.js servers on GoDaddy shared hosting.
I had similar problems getting socket.io to work with express. Here is a snippet from my working server code:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
// to allow cross-origin requests
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
//...
});
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(process.env.PORT, process.env.IP, function() {
console.log("Listening!");
});
io.on('connection', function (socket) {
console.log("Got connection!");
//...
});
It's slightly different from what you have, and may do the trick. Otherwise, your problem probably isn't with the node.js code.
This was hosted on a free Cloud9 workspace. I've also had node servers on Heroku... you should try one of those platforms, as they have official support for node.

Using net module in socket.io browser keeps loading

I want to use the tcp net module in node.js, my clients will be browser and also not browser ( device ).
when I tried to run in the browser the index.html, my browser keeps loading looks like it looping..I dont know what's wrong in my code.
I tried use telnet it works fine, the problem is on the browser i cannot load properly the index.html
//app.js
var net = require('net');
var io = require('socket.io')(net);
var clients = [];
var server = net.createServer(function (socket) {
console.log("New client connected");
clients.push(socket);
});
server.listen(1337, 'localhost', false, function () {
console.log('server bound');
});
io.on('connection',function(socket){
socket.emit('news', { hello: 'world' });
});
here is my client code.
http://pastie.org/10115599
Both the browser and socket.io require an http server, not just a TCP server. You can see the code examples in the socket.io documentation. The first server and client code example on that doc page shows you the basics you need.
In fact, the first step in socket.io connection is an http request that is then "upgraded" to the webSocket protocol. So, the server must be an http server. And socket.io hooks into an http server in order to receive incoming connections.
Here's a code example from the socket.io doc:
Server Code:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
app.listen(80);
io.on('connection', function (socket) {
// incoming socket.io connection established
});
function handler (req, res) {
// process http requests for normal web page serving
}
Client Code:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>

Do I need socket.io-client on browser-side of things?

EDIT: The answer appears to be no.
I'm new to Node.js, bower and Socket.IO and I'm not sure what I need for my purpose.
I'm making an app that has a frontend (where browsers connect) and a backend (a single Node.js server).
What do I need to create a Socket.IO server instance on the backend? What do I need on the client-side? Does the Socket.IO package contain both?
First install socket.io using below command
npm install socket.io
and the call socket.io in your server js File
var io = require('socket.io');
And the create connection in your server js file
var app = express();
app.get('/', function(req, res){
fs.readFile('index.html', function(Error,data){
res.writeHead(200,{'Content-Type':'text/html'});
res.write(data);
res.end();
});
});
server = http.createServer(app);
var IO = io.listen(server);
server.listen(3000);
IO.sockets.on('connection', function(socket) {
socket.on('msg_to_server', function(data) {
console.log(data);
});
});
Add this script inside head Tag in your index.html
<script src="/socket.io/socket.io.js"></script>
in your index.html create socketio connection
var socketio = io.connect("127.0.0.1:3000");
send some data to server following way
socketio.emit('msg_to_server',{ message : 'some data' });

Resources