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>
Related
I am trying to do something that sounds quite simple but unfortunately I can't manage to get right.
I just need to stream an image from a file with socket.io.
I have read several links that were either outdated or incomplete and here is where I am right now (not working) :
server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var fs = require('fs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.get('/',function (req,res){res.sendStatus(200)});
app.get('/image',function (req,res){res.sendFile(__dirname+'/index.html')});
http.listen(3000, function () {
console.log("server listening");
});
io.on('connection',function(socket){
console.log("socket connection");
var interval = setInterval(function(){
fs.readFile('./image.jpeg',function(err,buff){
if(err){
console.error(err);
}
else{
socket.emit('image',{image:true,buffer:buff.toString('base64')});
}
});
},1000);
socket.on('disconnect', function(){
console.log("socket deconnection");
clearInterval(interval);
});
});
index.html
<html>
<head>
<meta charset="UTF-8">
<title>IMAGE</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(function(){
var socket = io();
var ctx = document.getElementById('canvas').getContext('2d');
socket.on('image',function(info){
if(info.image){
var img = new Image();
img.onload = function () {
ctx.drawImage(img, 0, 0);
};
img.src = 'data:image/jpeg;base64,' + info.buffer;
console.log("Image received");
}
})
});
</script>
</body>
</html>
I have also tried several other configurations close to this one for the client file but none of them worked.
I read the file at interval because in the real project the image.jpeg file will change at times.
Thank you very much if you can help !
Sending images over a socket is not very efficient. I stumbled upon something similar when I had to send big buffers of game world data to every client. Sending those packets over a socket connection was obviously not an option for me.
I solved it by storing a key that referenced to a specific file on the server, and only sending that key to the client. Then the client would send a request containing the key to a http server, which eventually would respond with the file.
Here is some shortened code just to illustrate:
On the server:
...
const files = {};
...
...
function (request, response) { // http request function
const key = request.url.parse(key);
const file = fs.readFile(files[key]);
response.send(file);
}
...
...
function sendFile (socket, file) { // function that sends and stores the key
const key = generateKey();
files[key] = file;
socket.send('key', key);
}
...
...
sendFile(socket, '/path/to/file'); // send key to socket
...
This way the big files are being downloaded over http instead of the socket.
On the client:
...
socket.on('key', function (key) {
fetch('/file/' + key, function (response) {
const file = response.blob(); // blob or whatever
});
});
...
Hope this helps you :D
I found a coding from tutorials point to run a a simple socket.io chat server in localhost, I installed necessary environments like nodejs, express, init package.json and I started the server from terminal using command-"node app.js", then I accessed the index page in my localhost it showed the chat page, it is working fine. But the thing is I want to use this is in a live server for my office, to chat within the office. Is this code is enough for that. I am new to this socket.io and nodejs. My office has live server for hosting their website, this code opens and listens to port 3000. It will be highly helpful if you could tell me how to run this in a real server.
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
</head>
<script src = "/socket.io/socket.io.js"></script>
<script>
var socket = io();
function setUsername() {
socket.emit('setUsername', document.getElementById('name').value);
};
var user;
socket.on('userExists', function(data) {
document.getElementById('error-container').innerHTML = data;
});
socket.on('userSet', function(data) {
user = data.username;
document.body.innerHTML = '<input type = "text" id = "message">\
<button type = "button" name = "button" onclick = "sendMessage()">Send</button>\
<div id = "message-container"></div>';
});
function sendMessage() {
var msg = document.getElementById('message').value;
if(msg) {
socket.emit('msg', {message: msg, user: user});
}
}
socket.on('newmsg', function(data) {
if(user) {
document.getElementById('message-container').innerHTML += '<div><b>' +
data.user + '</b>: ' + data.message + '</div>'
}
})
</script>
<body>
<div id = "error-container"></div>
<input id = "name" type = "text" name = "name" value = ""
placeholder = "Enter your name!">
<button type = "button" name = "button" onclick = "setUsername()">
Let me chat!
</button>
</body>
</html>
app.js Server
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');
});
users = [];
io.on('connection', function(socket) {
console.log('A user connected');
socket.on('setUsername', function(data) {
console.log(data);
if(users.indexOf(data) > -1) {
socket.emit('userExists', data + ' username is taken! Try some
} else {
users.push(data);
socket.emit('userSet', {username: data});
}
});
socket.on('msg', function(data) {
//Send message to everyone
io.sockets.emit('newmsg', data);
})
});
http.listen(3000, function() {
console.log('listening on localhost:3000');
});
You can solve your problem through nginix( A reverse proxy server). Nginx have .conf file which contains the server realted configuration.
server { listen 3000; server_name io.yourhost.com; }
To run:
Sudo service nginx start
It will start your server on given IP or Domain name.
Change the declaration variable socket by
var socket = io(Server IP + ':port');
Example:
var socket = io('127.0.0.1:3000);
I using socket.io version 2.0.2
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>
I'm developing a server app in Node.js. For better understanding I wrote a very light code just to better point my issue. This is the server-side:
Server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 80;
var room = function(){
this.users = {};
this.counter = 0;
}
app.get('/reg',function(req,res){
console.log(req.params);
});
app.use('/recosh', express.static(__dirname + '/public/'));
app.listen(port, function(){console.log('ReCoSh Server Starts...\n');});
So inside the "public" directory I wrote the two following client-side files:
room.js
var room = {
//notifica al server una nuova registrazione
register: function(data){
$.getJSON('/reg',data);
}
}
index.html
<!doctype html>
<html>
<head>
<script src="room.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
var register = function() {
room.register({
"username": $("#username").val(),
});
}
</script>
</head>
<body>
<div id="step1">
<input id="username">
<button onclick="register()">register</button>
</div>
</body>
</html>
The problem is that by inserting an username and clicking on register, the code console.log(req.params); on the server just print {}. It seems the object is empty... If I try console.log(req.params["username"]) it prints undefined.
Why this simple object is not visible by the server?
First of all you should change a little typo in your code into this
room.prototype.addUser = function(username){
if(username){
this.users[username] = username;
this.counter++;
}
}
changing this.user[username] to this.users[username]
Then change app.use('/register'.. to app.get('/register'.., but I would recommend to use post method, but let's make work with little modifications and besides this you don't call the register function inside the callback. So you should do something like this:
app.get('/register',function(req,res){
var data = {
username: req.params['username']
}
room.addUser(data.username);
console.log('user added\n');
});
On the other hand in your client side the input id is equal to nickname whereas you get the value by username id, so you should make this change as well:
<input id="nickname"> to <input id="username">
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');