This is my app structure
controller
routes.js
public
jquery.js
socket.io.js
app.js
index.html
The app.js file contains the socket program which emits the some message when user connects. Now the problem was how I emit the message from routes.
My nodejs code was below:
This is my app.js file code:
var express=require('express');
var app=express();
var server=require('http').createServer(app);
var io=require('socket.io').listen(server);
app.use('/', express.static(__dirname + '/'));
io.sockets.on('connection',function(socket){
socket.emit('message',{msg:'hai'});
});
app.use('/cal',require('./controllers/route'));
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
server.listen(3000);
This is my route.js code:
var express=require('express');
var route=express.Router();
route.get('/',function(req,res){
//socket.emit('message',{msg:'hai'});
});
module.exports=route;
This is my index.html file code:
<htmL>
<head>
<title>Chat with socket.io and node.js</title>
</head>
<body>
<script src="./public/jquery.min.js"></script>
<script src="./public/socket.io.js"></script>
<script>
jQuery(function($){
var socket = io.connect();
socket.on('message',function(data){
alert(data.msg);
});
});
</script>
</body>
</html>
Thank You.
Routes has nothing to do with sockets. You have to listen on sockets, not on routes. Here's par of the docs (http://socket.io/docs/) for using Socket.IO with Express:
// server - app.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
// client - index.js
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
Related
Here is my code:
index.js
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');
});
app.get('/js/client_world.js', function(req, res){
res.sendFile(__dirname + '/js/client_world.js');
});
io.on('connection', function(socket){
console.log("A user is connected");
socket.on('disconnect', function(){
console.log("User disconnected");
});
});
http.listen(3000, function(){
console.log("Listenng to port 3000")
});
index.html:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="/socket.io/socket.io.js"></script>
<script src="//threejs.org/build/three.min.js"></script>
<script src="/js/client_world.js"></script>
</head>
<body>
<div id="container"></div>
<script>
var socket = io();
socket.on('connect', function(){
loadWorld();
});
</script>
</body>
</html>
and a third file, client_world,js, where I want to read data from a database.
The first line
var {Pool,Client} = require('pg');
causes an error.
Is this way to access the DB wrong? Thanks in advance for a hint.
I have problem with socket connection between client-side and server-side .
I have this code on server-side :-
var app = require('express')();
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('user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
and this code on client-side :-
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.1/socket.io.js"></script>
<script>
var socket = io();
</script>
</body>
</html>
the code in server-side is working , but in client-side i have these errors :-
can anyone help me to fix problem ?
Thanks a lot :(
Its looks like you are opening file directly into browser. Actually you are not specify path for serving your html. so that socketio can POST and poll data there.
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
If you really need to open file directly into browser rather than serving via nodejs on same port you have to specify host and port in client-side socket.
rather than simply using io() which will look for local port you can use this
var socket = io("http://localhost:3000");
So here how it works for me
// server
const app = require('express')();
const http = require('http').createServer(app);
// ^^^^^^^^^^^^
const io = require('socket.io')(http);
// here you should serve your index.html file
// and the socket io will know which socket to track
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');
});
// client/index.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<script src="/socket.io/socket.io.js"></script>
<script>
// here it automatically track localhost:3000
var socket = io();
</script>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
Hope it will help you
I want to use router functionality of node to call server side methods. I am not using express generator to generate project structure.
I made some changes to the code in the answer by Mukesh Sharma and made it work:
Server.js (Server code)
var express = require('express');
var app = express();
var routes = require('./FirstAppServer/route');
app.use('/', routes);
// //set static folder
app.use(express.static('FirstApp/public'));
app.use('/module', express.static('node_modules'));
app.listen(3000, function () {
console.log('Port 3000');
});
app.get('/', function (req, res) {
res.redirect('login.html');
});
module.exports = app;
route.js
var express = require('express');
var router = express.Router();
router.post('/endpoint', function (req, res, next) {
console.log('Server side call');
next();
});
module.exports = router;
test.html
<!doctype html>
<html>
<head>
<title>Login</title>
<script src="js/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
testServerCall();
});
function testServerCall(){
debugger;
$.ajax({
type:"post",
url:"/endpoint",
data:{
"a":"a"
},
success:function(){
console.log('success');
},
error:function(){
console.log('error');
}
});
}
</script>
</head>
<body>
<div id="divLogin">
<input type="text" id="txtUsername" />
</div>
<h2>Login</h2>
Create User
</body>
</html>
You can define routes in different file and can import in the server.js .
server.js - Server code
var express =require('express');
var apis = require('./api.js');
var app = express();
app.use('/api', apis);
app.listen(3000);
api.js - Api router
var express =require('express');
var router = express.Router();
router.get('/users', function (req, res) {
return res.json([{
name: 'John Doe',
email: 'john#doe.com'
}]);
});
module.exports = router;
Hope it helps you.
From a simple chat example at https://github.com/guille/chat-example/blob/master/index.js
For information, I'm not serving html file through following code, either the html is going to be embedded inside this iphone app or hosted somewhere. Question is how to connect the html to the nodejs environment where the sockets will be handled or is it a must that the html goes through the res.sendfile statement?
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
html
<script src="js/api/jquery-2.1.1.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
var socket = io();
socket.emit('chat message', "hello world");
});
</script>
I'm getting a 404 error, attached screenshot
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){
socket.on('chat message', function(msg){
console.log(msg);
io.emit('chat message', msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
You are using res.sendfile when it should be res.sendFile (capital F)
when starting app.js I get
$ node app.js
info: socket.io started
however, running index.html it says that it's missing
GET http://localhost:3000/socket.io/socket.io.js 404 (Not Found) localhost:5
Uncaught ReferenceError: io is not defined
I used npm install socket.io express
app.js
var express = require('express')
, http = require('http');
var io = require('socket.io');
var app = express()
, server = require('http').createServer(app)
, io = io.listen(server);
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.use(express.bodyParser());
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
Your code looks a bit messed up. Got it to work by changing it to this:
var express = require('express')
, http = require('http')
, app = express()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server)
;
app.configure(function(){
app.use(express.bodyParser());
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
server.listen(process.env.PORT || 3000);