socket.io not working for simple use case - javascript

var app = require("http").createServer(handler); // handler defined below
var io = require("socket.io")(app);
var fs = require('fs');
app.listen(8080);
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("Hell World");
});
}
io.on('connection', function(socket){
socket.on('dataChanged', function(data){console.log("Hello World")});
})
io.emit('dataChanged', 'this is a test')
//index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('dataChanged', function(data){console.log("Hello World")});
</script>
I am trying to implement this trivial feature but it is not working.Where am i going wrong i dont see the logs. socket events are not registered.

Alright three things here.
1. Your res.end is sending Hell world but it should send data
res.end("Hell World");
should be
res.end(data);
This is because we want to display the index.html file not a hello world
2. Your index.html is calling the socket.io js file wrong
<script src="/node_modules/socket.io/socket.io.js"></script>
should be
<script src="/socket.io/socket.io.js"></script>
This is because you cannot reference a file like that because there is no logic for it in your code. socket.io does however have the logic for it and can be called this way
3. Use emit on the client side
In your index.html change this code
socket.on('dataChanged', function(data){console.log("Hello World")});
to
socket.emit('dataChanged', 'this is a test')
and remove
io.emit('dataChanged', 'this is a test')
from your nodejs file
Now you can see Hello World from your console

When I was trying to create a simple chat using socket.io I had a conneciton problem, I assume that you have the same problem: I've used the same io.connect('http://localhost:8080') but later I tried using the IP address of my computer in WiFi network to connect from other devices (because localhost points to current device) - so the IP address of my computer in WiFi network was 192.168.0.103 -> io.connect('http://192.168.0.103') or io.connect('http://192.168.1.103'). I hope this works (the code was for Front-End side).

Related

MongoDB not showing console.log while inserting document from html form LOCALLY

I was trying to input Text data to a MongoDB database using just a HTML form. But when I ran it locally it doesn't work. I think this had something to do with creating a Node.js server. But I can't figure out how to run a HTML file (which is index.html here). I have only learned to run just the JavaScript code alone in the Node console. I don't know how I can run this index.html locally on NodeJS.
Also I want to do this without using ExpressJS! Everything I found online showed only on how to do this using ExpressJS. Is there a reason behind it? Can't we able to do this using just NodeJS and MongoDB? (LOCALLY on Windows)
var MongoClient = require("mongodb").MongoClient;
var url = "mongodb://localhost:27017";
function addData(){
var record = document.getElementById("title").value;
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("notetest");
var record2value = { title: record };
dbo.collection("page1").insertOne(record2value, function (err, res) {
if (err) throw err;
console.log("1 document added!");
db.close();
})
})
};
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="scripts/script.js"></script>
</head>
<body>
<form onsubmit="addData()">
<input type="text" name="title" id="title">
<input type="submit" name="submit" id="submit">
</form>
</body>
</html>
UPDATE: Also I tried calling this index.html using Node. By using the following code.
var http = require('http');
var fs = require('fs');
const PORT=8080;
fs.readFile('./index.html', function (err, html) {
if (err) throw err;
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(PORT);
});
But I don't know why I am not seeing the console.log from MongoDB, which should say "1 document added!".
Everywhere is using ExpressJS for this issue because we need a web server which can listen to the calls from network (Local or internet) and make it understandable in server side. You ran a http server on your own, but you need to handle request which are coming from clientside web. Due to your purpose, we need express too. Express also uses http library for creating a web server so you don't need to get worried about all that stuff. I don't know your problem with express but i suggest using express and its recommended approaches for solving this issue.
Update
This topic will help you for creating a web server just with Node.js:
Node.js server that accepts POST requests
Create a file called server.js and use above answer to create http server and then run it from a terminal with node app.js command. (Make sure that your terminal is in right directory)
Put your database related code in that section which accepts request under POST method.
Then create a javascript file for your HTML page and link it as you know with <script src="">... and simply use fetch API for sending request that http server that you just ran. Read about fetch here.

Connecting Node.js script to a front-end project

As a javascript newbie, I want to create a front-end project with a very little backend solution using Node.js.
I have a user inteface with some variables and a button. These variables have to be passed to a simple .txt file(on my filesystem) and overwrite its content. For this, I'm using a nodejs script:
var fs = require('fs');
fs.writeFile('log.txt', 'This is my text', function (err) {
if (err) throw err;
console.log('Replaced!');
});
But I want this to work onClick, whereas this only works from the command-line.
So I have the two following problems:
I want to update the .txt file with the button click. So basically the above written code has to be executed, when I click the button. But I don't understand, how to connect the front-end with this nodejs file.
I want the content to be dynamical. I'm sure, once the first problem is solved, this will be straightforward, but right now I don't know this either.
I'm 100% sure I'm missing something(maybe a web-server, but even then, how?). I did my research but all I found was either an overkill or I didn't even understand it. Any help would be appreciated, a tutorial, an advice or just a keyword, that I can use for my research.
Have a look at express. It's a "Fast, unopinionated, minimalist web framework for node". With this you can build a small webserver:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
});
app.listen(3000); // Webserver is running on port 3000
If you run it and got to your browser on http://localhost:3000, it would print Hello World.
Now what you would do is calling your logging function every time a specific URL is requested.
var fs = require('fs');
function log(text, callback) {
fs.writeFile('log.txt', text, callback);
}
app.get('/', function (req, res) {
log('This is my text', function (err) {
if (err) throw err;
res.send('Replaced!');
});
});
Now when you click the button you need to make an AJAX request to the server (maybe using jQuery).
Node.js doesnt have a built in front-library like some other scripting languages such as Python or VB. To create a node.js your intuition was correct in that you will need your app to expose itself as a web-server.
The popular library to do this is called express and it is very easy to get started.
I suggest that you follow the express quickstart tutorial to get into it.
From here you can wrap your code inside a route of the webserver (say /save) for example
var fs = require('fs');
var express = require('express');
var app = express();
app.get('/save', function (req, res) {
fs.writeFile('log.txt', 'This is my text', function (err) {
if (err) throw err;
console.log('Replaced!');
res.send('Replaced!')
});
})
app.listen(3000, () => console.log('Example app listening on port 3000!'))
With this example with the dependencies installed opening localhost:3000/save in your browser would cause your code to be run.

Node js and Socket.io Problems

First of all i've done some tutorials like:
https://socket.io/docs/
&
http://www.programwitherik.com/getting-started-with-socket-io-node-js-and-express/
&
a chat tutorial which i closed already so no link there.
But for all of them its the same. The Folder node_modules exists, the server is running (named app.js or index.js) and the index.html opens. But in every version and every test i dont get it to communicate from client to server. In one of these many questions here wrote someone about a funny installation path. So could it be that something is missing or installed in the wrong folder, needs extra permission or something like that?!
I also installed nodejs new, setup a path like others did in users/apps/ but also the same problems. Where could i find out what went wrong?! Is there a way to trace if the server got all files at the right point?!
The codes are verry basic, just hello world stuff. So i wonder why this wont work.
EDIT:
There is no very special code to share with you. Its the basic!
Server (app.js)
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var 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.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Client (index.html)
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
And in my case just for this one sample from the socket.io docs its the port. If i change it to 1337 it would refuse the connection. (just testing with crome without any changes in the browser or something like that) I will also test things like
var socket = io();
and many other things i read while searching about the solution. So maybe it helps other guys while they follow steps in tutorials where the port was changed without making it usable or open it. I think that was all the time the problem.
Im courious about how others have managed it, while writing a doc or tutorial about it but not one was going to tell that it could not work when there is something wrong with the port. Anyway, i'll update this with an edit2 - 3 and so on for the other tutorials i've made and will add also how it works with other ports, if nobody else do it here.
EDIT 2:
Works also perfectly fine now:
var socket = io();
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
and also
<script src="/socket.io/socket.io.js"></script>
Folders also work now:
Without
res.sendFile(__dirname + '/index.html');
/app
|- app.js
|- index.js
|node_modules
||- socket.io
||- express
also
res.sendFile(__dirname + '/client/index.html');
/app
|- app.js
|node_modules
||- socket.io
||- express
|client
||- assets
||- img
||- js
|server
||- js
Thanks to all who wanted to help.

Real time text using node.js

I have a node.js server that connects to an IRC channel. I can successfully output all messages from the channel to the console, but I'd like the messages to be displayed in real time on a webpage.
I am looking into socket.io but can't come up with anything, is this the best way?
All I need to know is how to update text on the webpage in realtime, I can see the messages if I refresh the page, but it is 1 message at a time.
I believe I need a client script for this, but I am unsure where to start. Thanks!
// Get the lib
var irc = require("irc");
// Create the bot name
bot.addListener("message#", function(nick, to, text, message) {
console.log(nick, " :=> ", text);
});
var http = require('http');
http.createServer(function (req, res) {
var bot = new irc.Client(config.server, config.nick, config);
bot.addListener("message#", function(nick, to, text, message) {
console.log(nick, " :=> ", text);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(text);
res.end(text);
});
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
socket.io is supporting serverside AND clientside communication through its inbuilt lib, when you start the server, the script is in
/socket.io/socket.io.js
And can be started with
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.connect('http://localhost:8080', { autoConnect: true});
</script>
See http://socket.io/get-started/chat/ for a simple chat application, should be easily able to implement IRC.

Node.js + socket.io: app on server not working correctly

I'm new to node.js and socket.io and tried to connect the server to the client with the example from http://socket.io/#how-to-use. (no localhost)
Server:
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'+err);
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.on('message', function(msg){
console.log('Got text: '+msg);
socket.broadcast.send(msg);
});
socket.on('disconnect', function () { });
});
Client:
<html><head><script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('connect', function () {
alert('connected.');
socket.on('message', function (msg) {
// my msg
alert('message received: '+msg);
});
socket.send('hi');
});
</script>
</head><body>This is the content :)</body>
</html>
Google Chrome displays in the console:
Unexpected response code: 502
Also, after receiving every message, Chrome adds
GET http://[myServer]/socket.io/1/?t=1352313105809 socket.io.js:1659
Socket.handshake socket.io.js:1659
Socket.connect socket.io.js:1699
maybeReconnect
to the console.
Wheres the problem?
The examples from the How-To page all use port 80, which is common for serving websites.
However, you use port 8080 in your example.
Check your web browser's console if it even loads the socket.io script.
You may need to provide http://localhost:8080/socket.io/socket.io.js as explicit url and connect with io.connect('http://localhost:8080');
If the above does not work, please share some insight on what port your web server runs on.
There is no code to actually handle any incoming messages server-side in your (updated) example.
`socket.on('message', function(msg){
console.log('Got text: '+msg);
socket.send(msg);
});
should at the very least send the message back to the client - your alert is only triggered when the client receives a message. Does the node.js console output any incoming or sent messages? A few lines of my node.js console look like the following upon connecting.
debug - client authorized
info - handshake authorized ...
debug - setting request GET /socket.io/1/...
debug - set heartbeat interval for client ...
debug - client authorized for
debug - websocket writing 1::
debug - sending data ack packet

Categories

Resources