I created a express 3 app with the express generator and installed socket.io.
On app.js im emiting a message:
io.sockets.on('connection', function(socket) {
socket.emit('init', { msg: 'Welcome'});
});
At server side I wrote:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src='/socket.io/socket.io.js' />
<script>
var socket = io.connect('http://127.0.0.1:3000');
socket.on('init', function (data) {
console.log(data.msg);
});
</script>
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
</body>
</html>
If I run app.js It should print "Welcome" on the console, but its not priting anything. I checked if /socket.io/socket.io.js is accesed and it does.
When running the app I get:
info - socket.io started
Express server listening on port 3000
GET / 200 28ms - 472
GET /stylesheets/style.css 200 163ms - 110
debug - served static content /socket.io.js
Am I missing something? I followed the socket.io webpage examples, but it seems that server is running fine... maybe something at the client-side?
EDIT: I also tried var socket = io.connect('http://127.0.0.1', { port: 3000 } ); on the client side, and also running all socket client side from the body.
Doing a console.log on the io.sockets.on event gave nothing... so "connection" is never reached.
app.js:
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
var app = express();
var server = http.createServer(app)
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/', routes.index);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
var io = require("socket.io").listen(server)
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
});
index.html:
<script>
var socket = io.connect();
socket.on('news', function (data) {
console.log(data);
});
</script>
In your browser's console you should see an object containing "hello": "world".
adding a index.jade file to the example I posted before
server.js
var app = require('express')()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server)
server.listen(3000)
io.set('loglevel',10) // set log level to get all debug messages
io.on('connection',function(socket){
socket.emit('init',{msg:"test"})
})
app.get('/',function(req,res){
res.render('index.jade')
})
/views/index.jade
doctype html
html
head
script(src="/socket.io/socket.io.js")
script.
var sockets = io.connect()
sockets.on('init',function(msg){
alert(msg.msg)
})
Related
I am having one simple vue file (index.html)
<html>
<body>
<div id="example">
<p>{{ hello }}</p>
</div>
</body>
</html>
<script src="js/app.js"></script>
<script>
new Vue({
el: '#example',
data: { hello: 'Hello world!' }
})
</script>
When opening the index.html file in browser, it is printing Hello world. I need to deploy this in express server. Added server.js file as below,
const express = require('express');
const path = require('path');
const app = express();
const port = process.env.PORT || 1234;
// sendFile will go here
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '/public/index.html'));
});
app.listen(port);
console.log('Server started at http://localhost:' + port);
When running node server, browser is just rendering like below,
If I replace the <script src="js/app.js"></script> with <script src="https://cdn.jsdelivr.net/npm/vue#2.6.14/dist/vue.js"></script>, it is working fine. Dont know why it is not working when using Vue library as external file. Is there any way to achieve this? Thanks in advance.
Just add this line of code
app.use(express.static(path.join(__dirname, 'public')));
So you code would look like this
const express = require('express');
const path = require('path');
const app = express();
const port = process.env.PORT || 1234;
app.use(express.static(path.join(__dirname, 'public')));
// sendFile will go here
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '/public/index.html'));
});
app.listen(port);
console.log('Server started at http://localhost:' + port);
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');
});
});
Here's a minimal example of node.js/express.js/socket.io server. It shouldn't be serving anything but index.html from / path.
server.js:
var path = require('path');
var express = require('express');
var http = require('http');
var socketio = require('socket.io');
// create server
var app = express();
var server = http.createServer(app);
var io = socketio(server);
// set routes for express
app.get('/', function(req, res){
console.log('index.html is NOT served by static middleware');
res.sendFile(path.resolve(__dirname + '/../client/index.html'));
});
// start listening
server.listen(9000, function(){
console.log('listening on 9000');
});
I run it with node server.js command. It serves index.html as localhost:9000/ successfully.
But for some strange reason it also serves /socket.io/socket.io.js from node_modules directory, which it shouldn't. Why? Here's my index.html file:
index.html
<!doctype html>
<html>
<head>
<title>Websocket + RabbitMQ + Express</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script src="client.js"></script>
<div id="messages"></div>
</body>
</html>
If it's about simplicity, there's no need for socket.io and http if you're using express. Try this code below for your server.js:
var path = require('path');
var express = require('express');
var app = express();
app.get('/', function (req, res) {
console.log('index.html is NOT served by static middleware');
res.sendFile(path.resolve(__dirname + '/../client/index.html'));
});
app.listen(9000, function () {
console.log('Example app listening on port 9000!');
})
This way, only client will resolve socket.io and server will only be responsible for serving a static page
I have just started using node.js socket.io. I am working on a simple connection between client and server.
Here is my server code:
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var socketio = require('socket.io');
var app = express();
app.set('port', process.env.PORT || 1337);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', routes.index);
var server = app.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
var io = socketio.listen(server);
and this is the client code(http://smartican.com/nodetest.html):
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="socket.io.js"></script>
<script type="text/javascript">
var socket;
socket = io.connect("http://smartican.com:1337/");
$(function() {
alert(socket.transport.sessionid);
});
</script>
</head>
</html>
there seems to be a problem when connecting to the socket from client as line
socket = io.connect("http://smartican.com:1337/");
breaks the script.. I have tested and the socket is open
Your socket.io.js is the wrong javascript file. It's the server javascript not the client javascript. You want socket.io-client.js. Take a look at this answer.
I am receiving a 404 when trying to resolve '/socket.io/socket.io.js' from my Node server. I can't determine why.
My server configuration looks like this:
var express = require('express')
, engine = require('ejs-locals')
, app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
// use ejs-locals for all ejs templates:
app.engine('ejs', engine);
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs'); // so you can render('index')
app.use(express.static(__dirname + '/public'));
//define routes
...
app.listen(3000);
//socket io
io.sockets.on('connection', function (socket) {
socket.on('set nickname', function (name) {
socket.set('nickname', name, function () {
socket.emit('ready');
});
});
socket.on('msg', function () {
socket.get('nickname', function (err, name) {
console.log('Chat message by ', name);
});
});
});
At the client I have this:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
I am testing this locally (port: 3000). The Socket code is basically ripped off of the socket.io example to get something working. I have reviewed other posts and can't seem to find where I'm going wrong. Can someone help?
Thanks
Got it!
The HTTP server needs to be listing on the port (3000 in this case.) I then removed the app.listen(3000) as the address will already be in use and is not needed.
Thanks!
var express = require('express')
, engine = require('ejs-locals')
, app = express()
, http = require('http')
, server = http.createServer(app).listen(3000)
, io = require('socket.io').listen(server);