i downloaded this very simple socket.io example from: https://github.com/shapeshed/nodejsbook.io.examples/tree/master/hour12/example02
package.json:
{ "name" : "socketio_example"
, "version" : "0.0.1"
, "private" : "true"
, "dependencies" : { "socket.io" : "0.8.7" }
}
app.js:
var http = require('http') ;
var fs = require('fs') ;
var count = 0;
var server = http.createServer(function (req, res) {
fs.readFile('./index.html' , function(error, data) {
res.writeHead(200, { 'Content-Type' : 'text/html'});
res.end(data, 'utf-8');
});
}).listen(3000, "1xx.2xx.1xx.26");
console.log('Server is running');
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
count++;
console.log('User connected; ' + count + ' user(s) present.' );
socket.emit ('users' , { number : count }) ;
socket.broadcast.emit ('users' , { number : count }) ;
socket.on('disconnect', function() {
count--;
console.log('User disconnected; ' + count + ' user(s) present.' );
socket.broadcast.emit('users' , { number : count }) ;
});
});
index.html:
<!DOCTIME html>
<html lang='en'>
<head>
<title>Socket.IO Example</title>
</head>
<body>
<h1>Socket.IO Example</h1>
<p id='count'></p>
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io.connect('http://1xx.2xx.1xx.26:3000') ;
var count = document.getElementById('count');
socket.on('users', function(data) {
console.log('Got update from the server!');
console.log('There are ' + data.number + ' users!');
count.innerHTML = data.number;
});
<script>
</body>
<html>
and then did:
node install ;
and finally:
node app.js &
then when i tried this using localhost (127.0.0.1), i can see my html code by doing:
curl http://127.0.0.1:3000 ;
then i changed the IP number from 127.0.0.1 to my own. and restarted the app. this command:
curl http://1xx.2xx.1xx.26:3000 ;
once again shows me the html code.
this project is supposed to display a count of the number of connections, but i cannot seem to get it working properly. however, i am not getting any errors either. the webpage is coming up when i browse to http://1xx.2xx.1xx.26:3000/ and the title appears but nothing else, no user count.
when a webpage connects i do this this message on the server:
debug - served static content /socket.io.js
any suggestions or thoughts what i might be doing wrong?
thank you all!
I too was having a lot of trouble wrapping my head around some of the examples I was seeing out there of socket.io, so I tried to break it down as simply as I could. Maybe this may help you as well.
I adapted this example from the example posted here: http://socket.io/get-started/chat/
First, start in an empty directory, and create a very simple file called package.json Place the following in it.
{
"dependencies": {}
}
Next, on the command line, use npm to install the dependencies we need for this example
$ npm install --save express socket.io
This may take a few minutes depending on the speed of your network connection / CPU / etc. To check that everything went as planned, you can look at the package.json file again.
$ cat package.json
{
"dependencies": {
"express": "~4.9.8",
"socket.io": "~1.1.0"
}
}
Create a file called server.js This will obviously be our server run by node. Place the following code into it:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
//send the index.html file for all requests
res.sendFile(__dirname + '/index.html');
});
http.listen(3001, function(){
console.log('listening on *:3001');
});
//for testing, we're just going to send data to the client every second
setInterval( function() {
/*
our message we want to send to the client: in this case it's just a random
number that we generate on the server
*/
var msg = Math.random();
io.emit('message', msg);
console.log (msg);
}, 1000);
Create the last file called index.html and place the following code into it.
<html>
<head></head>
<body>
<div id="message"></div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('message', function(msg){
console.log(msg);
document.getElementById("message").innerHTML = msg;
});
</script>
</body>
</html>
You can now test this very simple example and see some output similar to the following:
$ node server.js
listening on *:3001
0.9575486415997148
0.7801907607354224
0.665313188219443
0.8101786421611905
0.890920243691653
If you open up a web browser, and point it to the hostname you're running the node process on, you should see the same numbers appear in your browser, along with any other connected browser looking at that same page.
i installed a fresh linux on virtualbox and played with this. it worked fine running localhost but not over the net.
the answer was pretty obvious:
app.js -
original line 9&10:
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127 .0.0.1:3000/');
new line 9&10:
}).listen(3000);
console.log('Server running at port 3000/');
index.html:
original line 13:
var socket = io.connect('http://127.0.0.1:3000');
new line 13:
var socket = io.connect('http://1xx.2xx.3xx.1:3000');
Related
I'm trying to learn socket.io and Nodejs for the first time.
I have installed the nodejs and socket.io on my server in the root. everything is installed in the root.
on my domain, i created a test-folder and created an index.html file in that folder and placed this code inside it:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.2/socket.io.min.js"></script>
<script>
$(function(){
var iosocket = io.connect();
iosocket.on('connect', function () {
$('#incomingChatMessages').append($('<li>Connected</li>'));
iosocket.on('message', function(message) {
$('#incomingChatMessages').append($('<li></li>').text(message));
});
iosocket.on('disconnect', function() {
$('#incomingChatMessages').append('<li>Disconnected</li>');
});
});
$('#outgoingChatMessage').keypress(function(event) {
if(event.which == 13) {
event.preventDefault();
iosocket.send($('#outgoingChatMessage').val());
$('#incomingChatMessages').append($('<li></li>').text($('#outgoingChatMessage').val()));
$('#outgoingChatMessage').val('');
}
});
});
</script>
</head>
<body>
Incoming Chat: <ul id="incomingChatMessages"></ul>
<br />
<input type="text" id="outgoingChatMessage">
</body>
</html>
I then went back to the root and created an app.js file and placed this code in it:
var fs = require('fs')
, http = require('http')
, socketio = require('socket.io');
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-type': 'text/html'});
res.end(fs.readFileSync(__dirname + '/var/www/vhosts/my-website.net/httpdocs/test-folder/index.html'));
}).listen(8080, function() {
console.log('Listening at: http://localhost:8080');
});
socketio.listen(server).on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
});
And ran this command from the SSH:
node app.js
The command above retunr this:
Listening at: http://localhost:8080
I then opened the index.html file from the browser like so:
http://my-website.net/test-folder/index.html
but when i looked inside the console, i see the following error repeating over and over:
socket.io.min.js:1 GET http://my-website.net/socket.io/?EIO=3&transport=polling&t=1505580173244-3 404 (Not Found)
I have no idea what that means or what i need to do. could someone please advise on this issue?
any help would be appreciated.
Thanks in advance.
your first problem is inside your head tag.If you've installed socket.io there is no need to take it by link
let's replce this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.2/socket.io.min.js"></script>
with this one:
<script src="/socket.io/socket.io.js"></script>
Does anyone has experience to have Node.js and socket.io working on Cloud9 IDE?
The "Example (NodeJS with Socket.io)" (at https://c9.io/site/blog/2013/05/native-websockets-support/) doesn't work.
First, the server (https://c9.io/etlolap/webapp, /test.js) throws an error unless I fix as follow. I clicked Run button while test.js is on active tab.
var
socketIo = require('socket.io'),
io = socketIo.listen(Number(process.env.PORT));
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Then, my client (https://c9.io/etlolap/webapp, /test.html) still cannot connect. I clicked Preview button while test.html is on active tab.
<!doctype html>
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('https://webapp-c9-etlolap.c9.io');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
</head>
<body>
Loading...
</body>
</html>
and got error message below.
Failed to load resource: the server responded with a status of 404 --- (Not Found) https://c9.io/socket.io/socket.io.js
Uncaught ReferenceError: io is not defined --- test.html:6
1. Steps
1.1) Run server.js
The cloud 9 console shows up:
1.2) Hit Preview on index.html
1.3) Then a window is opening on the right side of your IDE. You can either hit the button in the middle of the navigation bar or copy and paste the url into a new browser window.
1.4) Socket communication is working!
2. Prerequisite
2.1) node module socket.io
Hit F6 or View -> Console and install socket.io.
2.2) the client side JavaScript from socket.io
Since I didn't find an official link to download it, I created a GitHubGist.
socket.io.js
3. Code
server.js
// module dependencies
var http = require("http"),
sio = require("socket.io");
// create http server
var server = http.createServer().listen(process.env.PORT, process.env.IP),
// create socket server
io = sio.listen(server);
// set socket.io debugging
io.set('log level', 1);
io.sockets.on('connection', function (socket) {
socket.emit('news', { message: 'Hello world!' });
socket.on('my other event', function (data) {
console.log(data.message);
});
});
index.html
<!DOCTYPE html>
<html>
<script src="js/socket.io.js"></script>
<script>
var socket = io.connect("https://demo-project-c9-matthiasholdorf.c9.io");
socket.on("news", function(data) {
console.log(data.message);
});
socket.emit("my other event", { message : "client emit" } );
</script>
</html>
Thanks for feedback from damphat and Matthias. After many failed attempts, finally I figured out the solution myself.
On Cloud9 IDE, the typical line in client (test.html here) has to be changed from,
<script src="/socket.io/socket.io.js"></script>
to
<script src="https://webapp-c9-etlolap.c9.io/socket.io/socket.io.js"></script>
The prefix is the URL of your Cloud9 project URL. By changing this line, my example worked.
you must flowing these step:
open the terminal on https://c9.io/etlolap/webapp, type:
npm install socket.io
node test
then open a new tab of browser with url
https://webapp-c9-etlolap.c9.io/socket.io/socket.io.js
You will see socket.io.js source code
I did not how you open test.html in c9.io without http server, did you just press preview?
Edit:
To return html files, you should merge http server and socket.io server like this:
// file: test.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen( Number( process.env.PORT ) );
function handler (req, res) {
fs.readFile(__dirname + '/test.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);
});
});
To fetch any html file requested, using html files located in the file folder, you can use express:
var fs = require('fs');
var express = require('express');
var app = express();
// This fetches html files from the client folder (if they exist), and returns a "Page could not be found" error otherwise (this can be customized to some other 404 error page as desired)
app.get('*', function (req, res) {
var urlReading = req.url;
if (urlReading == "/")
{
urlReading = "/index.html";
}
urlReading = __dirname + "/client" + urlReading;
console.log("Loading: " + urlReading);
fs.readFile(urlReading, function (err, html) {
if (err) {
console.log("Could not find " + urlReading)
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end("<html><head><title>Page could not be found</title></head><body><h1>Page could not be found</h1></body></html>");
}
else
{
console.log("Found " + urlReading)
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(html);
}
});
});
app.listen(process.env.PORT, process.env.IP);
hey i just started tinkering with node.js and am a complete noob. i am trying to get a simple client server communication going using socket.io and express (i have never used these before).
here is my code for the app(app.js):
var sys = require('sys'),
express = require('express'),
app = express('localhost');
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server);
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.send('Hello World');
});
app.listen(3000);
var socket = require('socket.io').listen(server);
socket.on('connection', function (client){
// new client is here!
setTimeout(function () {
client.send('Waited two seconds!');
}, 2000);
client.on('message', function () {
}) ;
client.on('disconnect', function () {
});
});
and here is my code for the client(client.html):
<html>
<p id="text">socket.io</p>
<script src="/socket.io/socket.io.js"></script>
<script>
$(document).ready(function(){
var socket = new io.Socket(),
text = $('#text');
socket.connect();
socket.on('connect', function () {
text.html('connected');
});
socket.on('message', function (msg) {
text.html(msg);
});
socket.on('disconnect', function () {
text.html('disconnected');
});
});
</script>
i got most of the code from:
NodeJS + socket.io: simple Client/Server example not working
and the changed it to be compatible with express 3.x
however when i run the server and open my client using chrome it tells me that it is unable
to load resource file:///socket.io/socket.io.js
i have already installed express and socket.io using npm
also i have read through atleast 20 similar posts and have not been able to find an answer
please help me. thank you
socket.io.js file needs to be served from port 3000, like localhost:3000.
So here is what you do change
<script src="/socket.io/socket.io.js"></script> to
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
Are you opening the client.html page directly from the local file system? The request for socket.io.js should look like http://localhost/socket.io/socket.io.js not file:///socket.io/socket.io.js.
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/
I'm playing around with nodejs and specifically looking at nowjs
I've got now up and running on a server running node and I have a separate web server. I successfully have the node server returning the client script and I reference this on the web server. This returns a 200 response code and all looks well. However I get javascript errors telling me that 'now' is undefined. As far as I understand it the 'now' variable should be available via the client script but this doesn't seem to be the case. Does anyone know if this set-up is possible? So the set-up is similar to the below pseudo code
//Server 1 node.com
if(request.url === '/nowjs/now.js'){
var file = 'path_to_clientlib/now.js';
fs.readFile(file, function(e, data) {
if (e) {
throw e;
}
response.writeHead(200,{'Content-Type': 'application/javascript'});
response.end(data);
}
and server.com
<script src="/jquery.js"></script>
<script src="http://node.com/nowjs/now.js"></script> <!-- This is returned properly -->
<script>
$(document).ready(function(){
now.receiveMessage = function(name, message){
$("#messages").append("<br>" + name + ": " + message);
}
$("#send-button").click(function(){
now.distributeMessage($("#text-input").val());
$("#text-input").val("");
});
now.name = prompt("What's your name?", "");
});
</script>
<div id="messages"></div>
<input type="text" id="text-input">
<input type="button" value="Send" id="send-button">
Straight away the console just returns 'now' is not defined
First of all there are enough modules that provide static file serving support, but if you want to manually serve a file I would do it like this...
var mime = require('mime') // Get mime type based on file extension. use "npm install mime"
, util = require('util')
, fs = require('fs');
function serveFile(filename, res) {
var filePath = process.cwd() + filename;
var stat = fs.statSync(filePath);
res.writeHead(200, {
'Content-Type':mime.lookup(filePath),
'Content-Length':stat.size
});
var readStream = fs.createReadStream(filePath);
return util.pump(readStream, res);
}
// Your code...
Or check out the module node-static on NPM or Github
About how to use NowJS (from the docs)
On the server
var httpServer = require('http').createServer(function(req, response){
// See code above how to serve static files...
});
httpServer.listen(8080);
var nowjs = require("now");
var everyone = nowjs.initialize(httpServer);
everyone.now.logStuff = function(msg){
console.log(msg);
}
On the client
<script type="text/javascript" src="http://localhost:8080/nowjs/now.js"></script>
<script type="text/javascript">
now.ready(function(){
// "Hello World!" will print on server
now.logStuff("Hello World!");
});
</script>