socket.io.js not found in express - node.js

my folder structure for socket.io is as following:
node_modules/socket.io/
my folder structure for socket.io.js is as following:
/node_modules/socket.io-client/dist/socket.io.js
var express = require('express');
var http= require('http').Server(express);
var io= require('socket.io') (http);
var app = express();
io.on('connection', function(socket){
socket.on('chat', function(msg){
io.emit('chat',msg);
});
});
io.on('disconnect', function() {
console.log('user is disconnected');
});
And view is as follows:
<script src="/node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="/js/jquery-2.1.4.min.js"></script>
<script>
$(function(){
var socket= io();
$('form').submit(function(e){
e.preventDefault();
socket.emit('chat', $('#input').val());
$('#input').val('');
return false;
});
socket.on('chat', function(msg){
$('#sent').append(msg);
});
});
</script>
and errors are:
Failed to load resource: the server responded with a status of 404 (Not Found)
Uncaught ReferenceError: io is not defined

Without creating server you are creating socket instance ,you can pass app to your socket.js or you can export socket to other module and use accordingly....It should be like this
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);

First off, a node.js server does not server ANY files by default. For a file to be served by the server, there must be a route handler that has code to send that particular file. So, that explains why this doesn't work:
<script src="/node_modules/socket.io-client/dist/socket.io.js"></script>
because there is no route handler in your server for the path "/node_modules/socket.io-client/dist/socket.io.js".
But, socket.io solves this problem for you. The socket.io server automatically installs a route for:
/socket.io/socket.io.js
And it will reach into that node_modules/socket.io/client directory and send the socket.io.js file when it sees the above request.
So, change your script tag to this:
<script src="/socket.io/socket.io.js"></script>
And, the socket.io server will automatically send the socket.io.js file from the dist directory.
It looks like your server initialization is also not correct because you don't pass express to your http server, you pass app. Change this:
var express = require('express');
var http= require('http').Server(express);
var io= require('socket.io') (http);
var app = express();
io.on('connection', function(socket){
socket.on('chat', function(msg){
io.emit('chat',msg);
});
});
io.on('disconnect', function() {
console.log('user is disconnected');
});
to this:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(80);
io.on('connection', function(socket){
socket.on('chat', function(msg){
io.emit('chat',msg);
});
});
io.on('disconnect', function() {
console.log('user is disconnected');
});
or, a bit simpler version:
var express = require('express');
var app = express();
var server = app.listen(80);
var io = require('socket.io')(server);
io.on('connection', function(socket){
socket.on('chat', function(msg){
io.emit('chat',msg);
});
});
io.on('disconnect', function() {
console.log('user is disconnected');
});

Related

Can't connection with socket server

I am trying to connection to socket server on port 8080 but keep getting this error Connection to IPAddress:8080 timed out!
this my server code
const express = require("express");
var http = require('http').createServer(app);
var io = require('socket.io');
const socket = io(http);
http.listen(8080, () => {
console.log(`Server is running on port ${PORT}.`);
});
how to solve it please ?
You have to write more code of socket you can not connect to socket direct
You have to write connection function
Follow This tutorial to know basics of socket
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var port = 8080; // set our port
app.get('/', function(req, res) {
res.sendfile('index.html');
});
io.on("connection", function (socket) {
// Everytime a client logs in, display a connected message
console.log("Server-Client Connected!");
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
http.listen(port, () => {
console.log('Magic happens on port ' + port); // shoutout to the user
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
</head>
<script src = "/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
<body>Hello world</body>
</html>
after running server check localhost:8080

Node js with express and socket.io - cannot find socket.io.js

I was working on a node js application with socket.io. I looked at some of the answers on SO but they could not help me with my problem. The error I am getting is
Failed to load resource: the server responded with a status of 404 (Not Found)
localhost/:10 Uncaught ReferenceError: io is not defined
Here is my directory structure:
Judgement
|----node_modules
|----|----express
|----|----socket.io
|----public
|----|----css
|----|----|----judgementMain.css
|----|----js
|----|----|----form.js
|----|----index.html
|----server.js
|----package.json
In my index.html page
I have the following link to socket.io.js
<script type="text/javascript" src="socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io();
</script>
<script type="text/javascript" src="js/form.js"></script>
The contents of server.js are as follows
var express = require('express');
var app = express();
var path = require('path');
// Define the port to run on
app.set('port', 3000);
app.use(express.static(path.join(__dirname, 'public')));
// Listen for requests
var server = app.listen(app.get('port'), function() {
var port = server.address().port;
console.log('Magic happens on port ' + port);
});
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function (socket) {
console.log('A user connected');
socket.on('disconnect', function() {
console.log('A user disconnected');
});
});
Can someone explain what I am doing wrong? I only just started with node js and express and socket.io, so any help is appreciated.
Thanks
I see a couple issues:
First, in your HTML, it should be src="/socket.io/socket.io.js" with the leading slash.
Second, you are creating two http servers but only actually starting one of them, when you should be using just one. Your socket.io stuff doesn't work because you're giving it an http server that you never started.
Change to this where you are giving socket.io the http server that express is using and that has been started on your desired port:
var express = require('express');
var app = express();
var path = require('path');
// Define the port to run on
app.set('port', 3000);
app.use(express.static(path.join(__dirname, 'public')));
// Listen for requests
var server = app.listen(app.get('port'), function() {
var port = server.address().port;
console.log('Magic happens on port ' + port);
});
var io = require('socket.io')(server);
io.on('connection', function (socket) {
console.log('A user connected');
socket.on('disconnect', function() {
console.log('A user disconnected');
});
});

How to connect socket.io in ExpressJS

Good morning why this code don't work (server respond but "io.on" no):
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
//this code not work in console // even it can not see
io.on('connection', function(socket) {
console.log('a user connect');
socket.on('disconnect', function() {
console.log('a user disconnect');
});
});
//server respond
http.listen(3000, function() {
console.log('Server running at 3000');
});
I'm a beginner, express and socket.io i downloaded by npm
You need to have a server as well as a client which will make a connection to the socket io server.
Based on what I understood from your code, I guess you want to do something like this:
First your server.js:
#!/usr/bin/env node
var http = require('http');
var express = require('express');
var app = express();
var io = require('socket.io');
var port = 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
var socketio = io.listen(server);
setInterval(function() {
console.log("Emitting..");
socketio.emit('data', {"x":"123"});
}, 2000);
module.exports = app;
Then your client.html: (I am writing a client, which will log into browser console.)
<html>
<head></head>
<body>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script>
var socket = io.connect("http://localhost:3000/");
socket.on('connect', function() {
console.log('connected');
});
socket.on('disconnect', function(){
console.log('disconnected');
});
socket.on("data", function(data) {
console.log(data);
});
</script>
</body>
That's it. Now start your server with node server.js and then, open up client.html in your browser and check console. Let me know, if there's anything unclear.

Nodejs : access socket.io instance in express routes files

I would like to be able to emit datas to clients connected to socket.io server from my express routes files.
My app.js looks like this :
var express = require('express');
var app = express();
//routes
require('./routes/test')(app);
// starting http server
var httpd = require('http').createServer(app).listen(8000, function(){
console.log('HTTP server listening on port 8000');
});
var io = require('socket.io').listen(httpd, { log: false });
io.on('connection', function(socket){
socket.join("test");
socket.on('message', function(data){
.....
});
});
module.exports = app;
My test.js file :
module.exports = function(app){
app.post('/test', function(req, res){
.....
//I would like here be able to send to all clients in room "test"
});
};
Simply inject your io object as an argument into the routes module :
app.js :
var express = require('express');
var app = express();
// starting http server
var httpd = require('http').createServer(app).listen(8000, function(){
console.log('HTTP server listening on port 8000');
});
var io = require('socket.io').listen(httpd, { log: false });
io.on('connection', function(socket){
socket.join("test");
socket.on('message', function(data){
.....
});
});
//routes
require('./routes/test')(app,io);
module.exports = app;
test.js :
module.exports = function(app, io){
app.post('/test', function(req, res){
.....
//I would like here be able to send to all clients in room "test"
io.to('test').emit('some event');
});
};

Nodejs include socket.io in router page

I have an express node app, and I'm trying to keep my code neat by not having all the socket.io stuff in app.js
I don't know the best way to go about this. Here is my initial thought which doesn't feel like the cleanest one
// app.js
var express = require('express')
, app = express()
, server = require('http').createServer(app)
, url = require('url')
, somePage = require('./routes/somePage.js')
, path = require('path');
app.configure(function(){...});
app.get('/', somePage.index);
and the route
// somePage.js
exports.index = function (req, res, server) {
io = require('socket.io').listern(server)
res.render('index',{title: 'Chat Room'})
io.sockets.on('connection', function(socket) {
...code...
}
}
I feel like I'm close but not quite there
I don't know if I'm reading that right but it looks like you are starting a socket server on every request for /, which I'm frankly a little surprised works at all.
This is how I'm separating out the socket.io code from app.js (using express 3.x which is a bit different than 2.x):
// app.js
var express = require('express');
var app = express();
var server_port = config.get('SERVER_PORT');
server = http.createServer(app).listen(server_port, function () {
var addr = server.address();
console.log('Express server listening on http://' + addr.address + ':' + addr.port);
});
var sockets = require('./sockets');
sockets.socketServer(app, server);
// sockets.js
var socketio = require('socket.io');
exports.socketServer = function (app, server) {
var io = socketio.listen(server);
io.sockets.on('connection', function (socket) {
...
});
};
Hope that helps!
a similar approach is to pass app into index.js file and initiate http and socketio server there.
//app.js
//regular expressjs configuration stuff
require('./routes/index')(app); //all the app.get should go into index.js
Since app is passed into index.js file, we can do the app.get() routing stuff inside index.js, as well as connecting socketio
//index.js
module.exports = function(app){
var server = require('http').createServer(app)
,io = require('socket.io').listen(server);
app.get('/', function(req, res){
});
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
io.sockets.on('connection', function(socket){
socket.on('my event', function(data){
console.log(data);
});
});
io.set('log level',1);
//io.sockets.emit(...)

Resources