I'm writing a chat application. In that, when the static file routing is working the socket.io (Chat) is not working throws not found error in console.
http://localhost/socket.io/?EIO=3&transport=polling&t=1486739955177-8 404 not found
When the chat is working fine then public static files is not working throws error
Cannot GET /public/index.html
The code chat working (public static files not working) :
var app=require('express')();
var http=require('http').Server(app);
var io=require('socket.io')(http);
var path=require('path');
//Initialize application with route
app.get('/',function (req,res) {
var express=require('express');
app.use(express.static(path.join(__dirname+'/public')));
res.sendFile(path.join(__dirname,'../public','chat.html'));
});
//Register events on socket connection
io.on('connection',function (socket) {
socket.on('chatMessage',function (from, msg) {
io.emit('chatMessage',from,msg);
});
socket.on('notifyUser',function (user) {
io.emit('notifyUser',user);
});
});
// Listen appliaction request on port 80
http.listen(80,function () {
console.log('Server Running in port 80');
});
The code public static files working ( chat not working) :
var app=require('express')();
var http=require('http').Server(app);
var io=require('socket.io')(http);
var path=require('path');
//Initialize application with route
var express=require('express');
app.use(express.static('public/'));
app.use('/public',express.static('public/stack'));
//Register events on socket connection
io.on('connection',function (socket) {
socket.on('chatMessage',function (from, msg) {
io.emit('chatMessage',from,msg);
});
socket.on('notifyUser',function (user) {
io.emit('notifyUser',user);
});
});
app.get('*', function(req, res){
res.send('what???', 404);
});
// Listen appliaction request on port 80
app.listen(80,function () {
console.log('Server Running in port 80');
}
Ok this code works
var express=require('express');
var app = express();
var path=require('path');
var server = require('http').createServer(app);
var io=require('socket.io')(server);
//Initialize application with route
app.use(express.static('public/'));
// app.use('/public',express.static('public/stack'));
//Register events on socket connection
io.on('connection',function (socket) {
socket.on('chatMessage',function (from, msg) {
io.emit('chatMessage',from,msg);
});
socket.on('notifyUser',function (user) {
io.emit('notifyUser',user);
});
});
app.get('/', function(req, res){
res.send('what???', 404);
});
// Listen appliaction request on port 80
server.listen(80,function () {
console.log('Server Running in port 80');
});
Move your chat.html in side public folder and access like http://localhost/client.html
Directory structure is like
appdir
public/client.html
server.js
node server.js
Related
I am trying to connect to a socket.io-client using this as my server.js:
var express = require('express');
var app = express();
var server = app.listen(3001);
var io = require('socket.io').listen(server);
app.get('/input', function(req, res){ // This is because in the server the port 3001 is open and I only can use the route 'input' to connect to the node server
res.send('Hello world');
});
io.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
And in my client file:
var socket = io.connect('https://urlofthepage:3001', {reconnect: true});
socket.on('connect', function() { console.log('connect'); });
// or (I tried with both)
var socket = io.connect('https://urlofthepage:3001/input', {reconnect: true});
socket.on('connect', function() { console.log('connect'); });
But when I go to urlofthepage/input show me
Hello world
but in the node server not show anything like
Client connected.
And in the page where I have the client.js file the console show me
3001/socket.io/?EIO=3&transport=polling&t=MBSSeZj net::ERR_CONNECTION_TIMED_OUT
Edit: It's on an online server, which has a wordpress installed, and my socket.io.js script is urlofpage/socket.io/socket.io.js
AND (I don't know if this matters, it is a test server, and the url has https, but it indicates that it is not secure, we have to change it)
I am trying to use sockets in my api. However I could not see the logs in the console.
The only output I see is:
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
We are live on8000
Here is my server.js file:
// server.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 8000;
var server = require('http').createServer(app);
var io = require('socket.io')(server);
const db = require('./config/db');
app.use(express.static(__dirname + '/../app'));
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url,(err,database) =>{
if (err) return console.log(err);
//check below line changed
require('./app/routes')(app, database);
app.listen(port,() => {
console.log("We are live on"+port);
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection',function(socket){
console.log('client connected');
socket.on('disconnect', function () {
console.log('disconnect');
});
});
})
and the index.html is:
<!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>
I see Hello world on the web browser, but I could not see 'client connected' on the console log.
Update: In your browser client you can see error in console.log http://localhost:8000/socket.io/socket.io.js 404 and (index):6 Uncaught ReferenceError: io is not defined
You have attach socket handler to a http server var io = require('socket.io')(server);, but in your code you start web server by express server
app.listen(port,() => {
console.log("We are live on"+port);
});
change it to
server.listen(port,() => {
console.log("We are live on"+port);
});
I have created a new .js file and listening to port 3000 instead of 8000 worked for socket.io
appsocket.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
//Whenever someone connects this gets executed
io.on('connection', function(socket){
console.log('A user connected');
//Whenever someone disconnects this piece of code executed
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Now I am able to see the logs on console when I call localhost:3000 instead of localhost:8000
I have a simple, local Nodejs server running Express. I'm using express-ws to set up a WebSocket endpoint. The client sends messages fine, and the server receives them, but when the server tries to send a message back, the connection closes and the client never receives the message.
This only happens over port 80. The connection stays open over port 3000, 8080, 443, and the client receives the messages the server sends back.
app.js
const express = require('express');
const path = require('path');
const app = express();
const expressWs = require('express-ws')(app);
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res, next){
res.send(`<script src="js/client.js"></script>`);
});
app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
console.log(msg);
ws.send(msg); //The connection doesn't close with this commented out
});
});
app.listen(80);
client.js
const ws = new WebSocket(`ws://${window.location.host}`);
ws.onopen = function(e){
console.log("WebSocket connected");
ws.send("testing 1");
ws.send("testing 2");
}
ws.onmessage = function(msg){
console.log(msg);
}
I'm at a loss. Any help would be appreciated.
I'm trying to implement socket.io on my server. This server is an API (express nodejs).
The server side is simple, but for the client side I'm using phonegap/cordova.
I don't use a phone to test what I do, I use my browser (chrome).
Si this the server side :
var express = require('express'); // call express
var app = express(); // define our app using express
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
console.log(socket);
socket.on('disconnect', function () {
console.log('socket disconnected');
});
io.emit('text', 'wow. such event. very real time.');
});
for now, this is simple,
But for the client side I am completely confuse (cordova phonegap),
This is what I have :
index.html
<script type="text/javascript" src="http://cdn.socket.io/socket.io-1.0.3.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) {
console.log('send')
socket.emit('my other event', { my: 'data' });
});
</script>
Nothing appears but errors like
GET http://localhost:8080/socket.io/?EIO=2&transport=polling&t=1462638049681-3 net::ERR_CONNECTION_REFUSED
and nothing on my server
any ideas to help me ? thanks :)
Your server is not listening on port 8080. That's why when you try to connect from browser to var socket = io.connect('http://localhost:8080');, it shows 'Connection Refused'.
This edit would work for you.
var express = require('express'); // call express
var app = express(); // define our app using express
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
console.log(socket);
socket.on('disconnect', function () {
console.log('socket disconnected');
});
io.emit('text', 'wow. such event. very real time.');
});
//Now server would listen on port 8080 for new connection
http.listen(8080, function(){
console.log('listening on *:8080');
});
I am trying to deploy my ext js app in node server. Steps i have followed.
1.Created a Extjs app using sencha cmd and had used sencha app build to build my app
Once after building successfully i have taken my app in build-->production folder to my node server folder.
below screenshot contains dbview(client) files
When i start my node server and run my applicaiton using http://localhost:3000 getting following error in my console
Please find my server code
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.sendFile(__dirname+"\\dbview\\index.html");
})
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
Help me with the problem
You need to mount the directory so that express knows to look for static content there, or you could go the long way about it and create a specific route handler for that file:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.sendFile(__dirname+"\\dbview\\index.html");
});
// THIS IS WHAT YOU NEED
app.use(express.static(__dirname));
// OR THE LONG WAY
app.get('/app.json', function(req, res) {
var options = {
root: __dirname,
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
res.set('Content-Type', 'application/json');
res.sendFile('app.json', options);
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
See the Express Documentation for further details.