Real time text using node.js - javascript

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.

Related

socket.io not working for simple use case

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).

Laravel Broadcast with Redis not working/connecting?

So I'm trying to broadcast Laravel 5 Events with the help of Redis. No I don't wanna use a service like Pusher since it's not free (even if the free limit would be enough for me) and I wanna keep control of the broadcast server.
So what I've done so far is, I'Ve set up a redis server (listening on port 6379 -> default), I've set up the following event:
class MyEventNameHere extends Event implements ShouldBroadcast
{
use SerializesModels;
public $data;
/**
* Create a new event instance.
*
* #return \App\Events\MyEventNameHere
*/
public function __construct()
{
$this->data = [
'power' => 10
];
}
/**
* Get the channels the event should be broadcast on.
*
* #return array
*/
public function broadcastOn()
{
return ['pmessage'];
}
}
I registered a route to that event:
Route::get('test',function()
{
event(new App\Events\MyEventNameHere());
return "event fired";
});
I've created (more like copied :P) the node socket server:
var app = require('http').createServer(handler);
var io = require('socket.io')(app, {origins:'*:*'});
var Redis = require('ioredis');
var redis = new Redis();
app.listen(6379, function() {
console.log('Server is running!');
});
function handler(req, res) {
res.writeHead(200);
res.end('');
}
io.on('connection', function(socket) {
console.log(socket);
});
redis.psubscribe('*', function(err, count) {
});
redis.on('pmessage', function(subscribed, channel, message) {
console.log(message);
message = JSON.parse(message);
io.emit(channel + ':' + message.event, message.data);
});
And I created the view to actually receive the broadcast (testview.blade.php):
#extends('layout')
#section('content')
<p id="power">0</p>
<script>
var socket = io('http://localhost:6379');
socket.on("pmessage:App\\Events\\MyEventNameHere", function(message) {
console.log(message);
$('#power').text(message.data);
});
console.log(socket.connected);
</script>
#endsection
I can launch the redis server without any problems.
I can launch the node socket.js server and I'm getting the response "Server running"
When I hit the route to the event I get the return "event fired" in my browser.
When I hit the route to the actual view
Route::get('test/view',function()
{
return view('testview');
});
I can see the whole page (layout is rendered), and the webconsole does not show any errors.
However if I fire the event, the view won't change, which means, the broadcast is not received right?
Now I included an output for the console
console.log(socket.connected);
which should show me if the client is connected to the socket.io right?
Well, the output says false. What am I doing wrong here?
Further information on my setup: I'm running the whole project on the php built-in server, the whole thing is running on Windows (if ever that could matter), my firewall is not blocking any of the ports.
EDIT 1:
I forgot to say that my node server is not receiving the messages as well... It only says "Server running", nothing else.
EDIT 2:
I used another socket.js:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
redis.subscribe('test-channel', function () {
console.log('Redis: test-channel subscribed');
});
redis.on('message', function(channel, message) {
console.log('Redis: Message on ' + channel + ' received!');
console.log(message);
message = JSON.parse(message);
io.emit(channel, message.payload)
});
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 time the console receives the messages.
So if the node socket.io receives the messages, then what's wrong with my client? Obviously the messages are being broadcasted correctly, the only thing is that they are not being received by the client...
I can't say what is exactly wrong and probably no one can't, because your problem is to broad and enviroment dependent. Using Wireshark Sniffer you can easily determinate part of solution that is not working correctly and then try find solution around actual problem.
If your question is about how to do that, I will suggest not involving node on server side and use .NET or Java language.
The problem with your code is you are connecting your client socket to the redis default port 6379 rather than the node port that is 3000.
So in your blade view change var socket = io('http://localhost:6379'); to var socket = io('http://localhost:3000');
have you tried to listen to the laravel queue, from command line, before to fire the event?
php artisan queue:listen

A severe memory leak with Socket.io 1.2.1 (and earlier)

I have a very simple socket.io server setup. My needs are to be able to communicate between server and client over sockets, but always on a one-to-one mode.
As such I created something simple as this on the client:
var socket = io();
socket.on('connect',function(){
socket.emit('connected', UserName);
});
And than on the server:
io.on('connection', function (socket) {
socket.on('connected', function (userName) {
if (userName !== null) {
socket.join("RoomFor:"+ userName);
}
});
});
So, each user has his own room I can now communicate with, and I can do this using my applicative userName (not socket id).
Now, on the same socket IO server, I also have express listening, with something like this:
app.get('/notify', function(req, res) {
var data = querystring.parse(req.url.split('?')[1]);
var userName = data.clientId;
io.sockets.to('RoomFor:'+ userName).emit('notice', {event: data.event });
res.writeHead(returnCode, {'Content-Type': 'text/plain'});
res.end();
});
So, a very simple server side signaling solution.
However, something in this setup is leaking badely, I have created heapdumps and tried to compare the results, but couldn't make out anything out of it.
Any thoughts?
(Btw, I went over all the threads related to node + socket.io memory leaks, none is my case... I don't use redis store, I am running with up to date node and socket.io versions.)

Node.js sockets, what happen if no FYN packet?

I have two node.js server, one of them connect via socket to the other and send data regulary.
Exemple could be:
client.js:
io = require('socket.io');
var socket = io.connect(IP_SERVER + ':' + PORT);
socket.on('connect', function () {
setInterval(socket.emit('data', new Date()), 60000);
});
server.js
var app = http.createServer(),
io = require('socket.io').listen(app);
app.listen(PORT);
io.sockets.on('connection', function(socket) {
socket.on('data', function(m) {
console.log(m);
});
});
Now, while the two are communicating, I shut down server.js (ctr-C for example). Is any event pop up in client.js? Is client.js will auto connect once server rebooted?
I ve tried on my own, by adding listener for 'end', 'error' and 'close'. None where started, but once server.js online, it got data anew... Can t I know when this happen?
UPDATE: Well, it seems it end up reconnecting, but the time it take seems random, I can t find anything about this in docs...
By default, it will try to reconnect after losing a connection. There is also a setting (reconnectionDelay) to let socket.io know how long to wait before attempting to reconnect, and there is also a setting (reconnectionDelayMax) that specifies the maximum amount of time to wait between reconnections. Each attempt increases the reconnection by the amount specified by reconnectionDelay.
Full documentation is here

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