socket.io not picking up subfolders - node.js

when I run socket.io locally let say http://localhost:8000/ this does not pick all the folders for css and js. here's my structure:
<head>
<script type="text/javascript" src="js/main.js"></script>
<link rel="stylesheet" href="css/main.css">
<script src="socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<script>
var socket = io.connect('http://localhost:8000');
$('.box').click(function(){
var content = $(this).attr('id');
//console.log(content);
socket.emit('click',content);
});
socket.on('test', function(content){
$(".box").css({"background":"grey"});
$(".one,.two,.three,.four").hide();
$("#"+content).css({"background":"red"});
$("."+content).fadeIn();
//$('.box').css({"background":"grey"});
});
</script>
server.js :
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs');
// creating the server ( localhost:8000 )
app.listen(8000);
// on server started we can load our client.html page
function handler(req, res) {
fs.readFile(__dirname + '/client.html', function(err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client.html');
}
res.writeHead(200);
res.end(data);
});
io.sockets.on('connection', function(socket){
socket.on('click', function(data){
io.sockets.emit('test',data);
});
});
console is throwing this below that it cannot be found:
"http://localhost:8000/css/normalize.css".
"http://localhost:8000/css/main.css".
Can someone help please?
second question:
I'm very new to this, so not sure if this does not sound stupid. But I would like to run this from actual directory let say: http://localhost/test/test2:8000 instead of http://localhost:8000/

You seem to be misunderstanding the role of Socket.io. This javascript library handles real-time communication between the clients and your server. In your code, you don't use Socket.io at all: you don't define any connection handler nor do you emit any event.
What you should do instead is modify the code of your HTTP server to serve the files. In your example, you have to edit the handler function that handles the incoming requests. Please look at the documentation for the HTTP module. Your app is an http.Server object. Your handler function, per the documentation, is:
The requestListener is a function which is automatically added to the 'request' event.
which handles an http.IncomingMessage. You should then look at the url property, which contains the URL that the client requested, in order to serve the correct file. In your example, you always serve the same file: client.html.
To conclude, I'd suggest that you should have a look at some javascript libraries that ease the creation of a webserver, for instance Express, or Hapi. This will be easier your you than to handle each request by hand.

Related

Node + Socket.io Connection issue

I'm having trouble connecting to socket.io. With the code below, I keep getting an 'io is not defined' error on my browser console. Anyone have any idea what I'm doing wrong here? I've been poking around stackoverflow for hours, but no solution seems to work...
server side:
,db = require("../../lib/db")
,config = require("../../config")
,app = require("../index")
,io = require('socket.io')(app);
;
io.on('connection', function (socket) {
console.log('connected')
});
exports.render = function(req, res){
console.log(io)
res.render("vitron", {});
}
client side:
<!doctype html>
<html>
<head>
<title>Sockets</title>
<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>
</head>
<body>
</body>
</html>
You apparently don't have the right server-side initialization so that your server will automatically serve the /socket.io/socket.io.js file.
There are many ways to do this, but the simplest way that is documented in the socket.io documentation is to use some built-in middleware that will have the socket.io server-side library automatically intercept the request for the /socket.io/socket.io.js file and serve up the script file.
The socket.io documentation shows exactly how to do this when using express with node. If you aren't using express, then you can do it with your own middleware. Or, if you're just using plain node, you will have to either handle that route yourself or just put the /socket.io/socket.io.js file in a known location that it can be requested directly from. You can even link to it on a CDN if you want, but there is an advantage to using the built-in scheme because when/if you upgrade the socket.io library on the server, it will automatically contain a matching client-side library which is kind of nice.
I don't know exactly what your overall setup is, but here's my socket.io initialization with express 4.
var express = require('express');
var app = express();
var server = app.listen(8081, function() {
console.log(new Date().toISOString() + ": server started on port 8081");
});
var io = require('socket.io').listen(server);

Access is forbidden for Node.js

I am trying to create a simple chat application using Node js. I am using a Windows operating system. As local server I am using Xampp. I have installed Node. I have also installed socket.io using package.json. The code in package.json is given below.
{
"name":"chat",
"version":"0.0.1",
"private":"true",
"dependencies":{
"socket.io":"0.9.16",
"express":"3.4.0"
}
}
Then I have written the code for the server. The Node server is running in port 1337. The code for the server is given below.
var io = require('socket.io').listen(1337);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Then when I run it, it is running. Then I have written the code for the client in a index.php file. The code for the client is given below.
<!DOCTYPE html>
<html>
<head>
<title>Chat app.</title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="/node:1337/socket.io/socket.io.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var socket = io.connect('http: // localhost / node : 1337');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
});
</script>
</body>
</html>
But when I try to the run it with a browser, all I get see in the console is that access is forbidden. All my files including node_modules is saved in C:\xampp\htdocs\node.
The code you're using is copied from the socket.io Home page and it's only used as an example, but it's not actually working code because the socket.io script isn't being bound to any server instance.
Socket.io isn't a server. It's just a library for nicely handling Websockets. In order to use socket.io you have to require HTTP or Express and create a server instance. Then you'll have to bind the server instance with socket.io.
For a working implementation on how to get socket.io up and running with your server, you'll have to look at the How To Use page. There they have these nice code example, depending on the implementation you're running (if it's HTTP, or something else).
So scratch the whole Xampp server idea. Node has it's own built in server capabilities and that's what you're meant to be using.
Here's a working example (from the socket.io website) of how Socket.io is meant to be used with HTTP. In this code snippet, the server is also created (and it's listening on port 80), so you won't have to worry about that:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Once your server's up and running, you can access it by typing localhost:80 into the browser.

NodeJS - long polling/pushing/rejeverse ajax? What do i need to push live data isntantly to the web?

Im fairly new to NodeJS(using c9.io) and have this sick obsession with it lately.
I would like to know while using NodeJS. Is it possible to stream the contents of a basic html page, not large, and not special to lets say 10 concurrent users. However if there is a change to that html page the users will instantly see the changes. This can be based on whatever event but basically on the file contents being updated. Im really hoping to create some simple prototype to impress the boss and do it with NodeJS with hopes to get ride of our current out-dated use of setInterval ajax posts. puke
What is the name of this process because i keep hearing different names.
Is it Possible?
What else would i need in addition to NodeJS
Where is a good starting point?
Thanks
Ok, here is a really simple example.
A textarea synchronizes with login members.
Please install http, socket.io and express(ver3).
sudo npm install http, socket.io, express
And create a javascript file.
server.js
var app = require('express')(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
member_sockets = {},
key;
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
var user_id = socket.id;
member_sockets[user_id] = socket;
console.log("[login]-->", user_id);
socket.on('txt_change', function (data) {
for (key in member_sockets) {
if (key != user_id) {
member_sockets[key].emit("txt_change", data);
}
};
});
socket.on('disconnect', function (socket) {
console.log("[logout]-->", user_id);
delete member_sockets[user_id];
});
});
In the same directory, you also create an index.html file.
index.html
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('txt_change', function (data) {
console.log(data);
$("#txt").val(data.txt);
});
$(document).ready(function(){
$("#txt").keyup(function(){
socket.emit('txt_change', { "txt" : $(this).val() });
});
});
</script>
</head>
<body>
<textarea id="txt" style="width:200px;height:100px"></textarea>
</body>
</html>
Then run the server with this command:
sudo node server.js
So the code should work like this picture:
Did you check socket.io? You can create the push server easily using socket.io module.
http://socket.io/

Can't find socket.io for client when server is created without handler

Browser can't find socket.io.js for client:
<script src="/socket.io/socket.io.js"></script>
When server is created without handler:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs');
app.listen(80);
//without this part:
/*function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}*/
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
I don't need and don't want handler function because everything I generate in PHP. And sometimes use client application functions for another file than index.html/php
So how to make browser can find socket.io.js?
I've wrote a demo app that you could have a look at if you don't want to loose to much time getting started with socket.io and Express 3.
To have websockets working your client js needs to be delivered from a webserver. This is one of those many browser limitation.
The easiest setup is to have a node server that provide both the client side Js and the WebSockets. Using easier the http module of Express (a bit overkill but super practical if you want to build something more than just a test app).
Other wise you need to have your client side js pointing to the right place. For example if you run your socket.io server of port 8080 and you deliver your static client side on port 8000 (using python -m SimpleHTTPServer for example or port 80 using a regular apache).
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
If you don't need access to http module functionality use this way:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Include this on your client side !
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
var io = io.connect();

Simple nodeJS example not working with socket.io

Have been struggling all day trying to make this simple example work using socket.io. I've tried initially on Windows 7 with Cygwin. Have since also tried on OS X, with the same result.
When running the script, it shows this...
2 May 20:57:47 - socket.io ready - accepting connections
But visiting the index.html page doesnt show a client has even connected.
index.html
<html>
<head>
<script type="text/javascript" src="socket.io.js"></script>
<script type="text/javascript">
var socket = new io.Socket('localhost',{'port':8090});
socket.connect();
socket.on('connect', function(){
console.log('connected');
socket.send('hi!');
});
socket.on('message', function(data){
console.log('message recived: ' + data);
});
socket.on('disconnect', function(){
console.log('disconected');
});
</script>
</head>
<body></body>
</html>
server.js
var http = require('http'), io = require('socket.io'),
server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Hello world</h1>');
});
server.listen(8090);
var socket = io.listen(server);
socket.on('connection', function(client){
console.log('client connected');
client.on('message', function(){
console.log('message arrive');
client.send('some message');
});
client.on('disconnect', function(){
console.log('connection closed');
});
});
Any ideas on what I could be doing wrong? No console messages whatsoever are being displayed. Notably, when i use Firebug to look at the index.html page, no scripts are being embedded, which is odd..Not sure what could be causing that.
You're not loading the socket.io library properly in your index.html file. Try this:
<script type="text/javascript" src="http://localhost:8090/socket.io/socket.io.js"></script>
You're not serving up socket.io.js (or the flash file).
I'd recomend using the CDN:
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
or alternatively use express to serve the socket.io.js file.
edit:
err actually looking closer you're also not serving up index.html
again express could work but for the simple example:
var fs = require('fs');
var index = fs.readFileSync('index.html');
//note the readFileSync is done only in the first tic
.
.
.
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
Use this on the client side as the path !
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
yes, and comment the following line:
// server.listen(8090);

Resources