Socket.io Multiple Connections on Client Side - node.js

I am trying to have a multiple socket io connections on the same page (client side). I have tried this answer but unfortunately it did not solved the problem, Link to SO question
Case:
I have a chat(bot) application running on localhost:3000
I have a CMS for the said chat(bot) application running on localhost:8000
My code currently:
1.Declare Script on index.html, (on localhost:3000)
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="js/main.js"></script>
2. Socket.io logic on main.js (on localhost:3000)
var socket = io('http://localhost:3000', {resource: '/socket.io', forceNew : true});
var cms_socket = io('http://localhost:8000', {resource: '/socket.io', forceNew : true});
socket.on('connect', console.log("SOCKET IO chat connected")) //WORKED
cms_socket.on('connect', console.log("SOCKET IO cms_connected")); //WORKED
socket.on('bot-reply', (data) => alert(data)) //WORKED
cms_socket.on('test_cms_socket', (data) => alert(data)) //NOT-WORKED
What confuses me is that the console log from both socket worked, telling both socket connects, though the cms_socket.on('test_cms_socket', ..) did not work.
Here is the logic from the CMS localhost:8000
function broadcast(req,res){
res.io.emit('test_cms_socket', "This is from CMS");
return res.redirect('/');
}
I have passed my socket.io to the middleware, used a tutorial from here
I do not really know if this helps or not, but I get this error from console. Any help would be very much appreciated
Uncaught TypeError: Cannot read property 'apply' of undefined
at r.emit (index.js:133)
at r.emit (socket.js:136)
at r.onconnect (socket.js:327)
at r.onpacket (socket.js:224)
at r.<anonymous> (index.js:21)
at r.emit (index.js:133)
at r.ondecoded (manager.js:345)
at s.<anonymous> (index.js:21)
at s.r.emit (index.js:133)
at s.add (index.js:241)

Related

I cannot connect to a sites socket

I've been trying to do this but can you connect to another websites their socket.io server? I've been trying to scrape data from a website that uses socket.io for live updates. It would be very handy if this were to be possible.
I'm trying to get live updates from the website https://www.ethercrash.io/ - However I tried the following code and wouldn't get any updates other than a connection;
var io = require('socket.io-client');
var socket = io('https://www.ethercrash.io')
socket.on('connect', function(){
console.log(true);
});
socket.on('msg', function(data) {
console.log('chat message');
});
socket.on('disconnect', function(){
console.log(false);
});
Am I doing something wrong or is this just not possible?
I use the following in all my node.js / express / socket.io projects. Hopefully it helps you out.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script>
$(document).ready(function() {
// NOTE, I AM FORCING WEBSOCKET TRANSPORT HERE. AND AM NOT ALLOWING
// SOCKET.IO TO FALL BACK TO LONG POLLING FALLBACK,
// SO YOU CAN REMOVE THE TRANSPORTS AND GO WITH SOCKET.IO DEFAULTS
// PORT I'M USING IS 3000 -- SO THE PORT CAN BE IMPORTANT, DEPENDING ON YOUR USASGE
var socket = io.connect("https://MY-SERVER-NAME-HERE.eastus.cloudapp.azure.com:3000", {
secure: true,
transports: ["websocket"],
path: "/socket/socket.io"
});
// EVERY TIME THE NODE.JS SERVER SENDS US 'MESSAGE' WE'LL DISPLAY THAT UPDATED NUMBER IN A DIV
socket.on("message", function(msg) {
document.getElementById("message").innerHTML = msg;
});
});
</script>
</head>
<body style="width: 100%;">
<div id="message" style="text-align: center; width: 100%; font-size: 2em;"></div>
</body>
</html>
You also are depending on that 'other site' (running the socket server) emitting out to either ALL connected clients or to your connection specifically. Unless either of those happen, you will only have a connection with no messages being emitted out (to be read / parsed).
Sockets are really fun to work with and full of potential once you get the hang of it!

Trying to create a socket between servers with SocketIO and PHPws

I'm having a bit of an issue with websockets. So, I have a Rpi that provides me some data through a socketIO client in a pretty simple way. The following code shows how do I get to get this data:
<!DOCTYPE html>
<html>
<header>
<title>SocketIO test</title>
<script src="http://192.168.5.5:8000/socket.io/socket.io.js"></script>
</header>
<body>
<script type="text/javascript">
var client = io.connect('http://192.168.5.5:8000');
client.on('connect', function() {
console.log('connected');
});
client.on('raw', function(data){
console.log(data);
});
client.on('state', function(data){
console.log(data);
});
</script>
</body>
However, what I need to implement is a little bit more complex. I need to use a Apache server to trait some of the data before it gets to the client side. The following image shows what I attempt to build:
To reach my goal I tried several WebSocket Servers and Client libraries for PHP until I found PHPws, which looks like the best solution for my scenario.
So, I read the examples, I test them and everything went well until I tried to connect to the Rpi with the following code:
require_once("../vendor/autoload.php");
$loop = \React\EventLoop\Factory::create();
$logger = new \Zend\Log\Logger();
$writer = new Zend\Log\Writer\Stream("php://output");
$logger->addWriter($writer);
$client = new \Devristo\Phpws\Client\WebSocket("ws://192.168.5.5:8000", $loop, $logger);
$client->on("connect", function() use ($logger, $client){
$logger->notice("Or we can use the connect event!");
$client->send("Hello world!");
});
$client->on("raw", function($message) use ($client, $logger){
$logger->notice("Got message: ".$message->getData());
$client->close();
});
$client->open()->then(function() use($logger, $client){
$logger->notice("We can use a promise to determine when the socket has been connected!");
});
$loop->run();
I've more or less taken this example from Devristo's github.
From the server side, the execution of the program is not throwing any error or message.
Is it possible to build what I want to build here with PHPws?
If so, am I connecting properly to de Rpi server with PHPws sample code shown?
It is possible :
[Node] Socket Server (This would be your RPi)
Simple socket.io server in node to check for a
(success) client connection event.
var io = require('socket.io')(1337);
io.on("connection",function(socket){console.log("[+] client",socket.id);})
[PHP] Socket Client
Using Elephant.IO we setup a client (Client Example for Socket.IO v2.0)
<?php
use ElephantIO\Client;
use ElephantIO\Engine\SocketIO\Version2X;
require __DIR__ . '/vendor/autoload.php';
$client = new Client(new Version2X('http://localhost:1337', [
'headers' => [
'X-My-Header: websocket rocks',
'Authorization: Bearer 12b3c4d5e6f7g8h9i'
]
]));
$client->initialize();
$client->emit('broadcast', ['foo' => 'bar']);
$client->close();
With this simple Client/Server example you will see the 'on connection' event in the node server when the browser opens the client.php

Use the same socket.io connection in multiple HTML pages in node js

-Follwing is the jquery code I have written in my (dashboard.html) file
<script>
$(function(){
$("#username").hide();
var socket= io.connect();
$(document).on("click", ".help", function () {
alert( $(this).attr('id'));
socket.emit('help',{helper:$username.val(),requester:$(this).attr('id')});
});
});
---On clicking help button socket will emit an event "help" as you can see in the code.
---Following is the app.js file on server
io.sockets.on('connection',function(socket){
socket.on('help',function(data){
console.log('rohi is goood',data.helper);
socket.emit('loadList' , {helper:data.helper,requester:data.requester});
});
});
---On "help" event socket is emitting an event "loadList" in app.js file.
Now I want to use "loadList" event in some other html file like "chat.html".
The code I have written is as follows for chat.html.
<script>
$(function(){
// var socket= io.connect();
// var socket= io.connect('http://localhost:3000/', { 'force new //connection': true });
socket.on('loadList',function(data){
alert('inside help',$('#usernam').val());
console.log('tatai',$('#usernam').val());
if($('#usernam').val()== data.helper){
$('#chatList').append('<p>'+data.requester+'</p>'+'<button value="chat"></button>');
}
else if($('#usernam').val() == data.requester){
$('#chatList').append('<p>'+data.helper+'</p>'+'<button value="chat"></button>');
}
else {
alert('fuck off');
}
});
The above code is not working. Please tell me how can I use same socket connection in the chat.html file.(loadList event is not working).
As your question is not complete so i am assuming you want to know if socket.io connection can be used on different html pages . Yes you can access it on every html page of your application as long as you have one server on which socket.io is used .
Every time a new user comes a socket session is created for that particular user and that user can access any page of your application .

socket.io node.js server "debug: destroying non-socket.io upgrade" message

I have a node.js socket server using socket.io.
I'm building a firefox addon, where I load a pageworker. The html in the following page is as follows:
<html>
<head>
<script type="text/javascript">
//THIS DOESN'T WORK
var exampleSocket = new WebSocket("ws://someip:port");
exampleSocket.onopen = function (event) {
console.log("socket opened!");
};
//THIS WORKS
var exampleSocketa = new WebSocket("ws://echo.websocket.org");
exampleSocketa.onopen = function (event) {
console.log("socket to echo opened!");
};
</script>
</head>
<body>
</body>
</html>
I can open a websocket to echo.websocket.org, but not my own server. I get a "debug: destroying non-socket.io upgrade" message. I can switch it off with the option: { 'destroy upgrade': false }, but then I see no debug output from server, and no connection is made.
What am I doing wrong? How can I get a socket open to my socket.io server?
So after some more googling, it turns out that I need to require socket.io on the client side. Even though socket.io uses websockets, it prefers talking to itself.

Node.js: Socket.io doesn't work

I've wrote a simple node.js app by socket.io some weeks ago. My program is fine on my PC but when i tried to run it on my laptop. I faced a really weird error on my console.
note that I'm running node on 127.0.0.1:2324. I don't know what is that ip (0.0.9.20) on the chrome console.
Again, my code is correct cause it's working fine on my PC.
And I get this on my cmd:
my paint.html code is something like this:
<script src="http://127.0.0.1/node/paint/js/jquery.js"></script>
<script src="http://127.0.0.1/node/paint/js/cursor.js"></script>
<script src="http://127.0.0.1/node/paint/js/controllers.js"></script>
<script src="http://127.0.0.1/node/paint/js/core.js"></script>
<script src="http://127.0.0.1:2324/socket.io/socket.io.js"></script>
<link href="http://127.0.0.1/node/paint/css/style.css" rel="stylesheet" />
core.js:
// broadcat function
function broadcast(data)
{
var socketio = io.connect(serverPort);
socketio.emit("message_to_server", { pen : data});
}
// receive data from server
var socketio = io.connect(serverPort);
socketio.on("message_to_client", function(data)
{
var res_brush = data['pen'];
var brush_data_rec = res_brush['pen'].split('|');
draw(brush_data_rec[0],
brush_data_rec[1],
brush_data_rec[2],
brush_data_rec[3],
brush_data_rec[4],
brush_data_rec[5],
brush_data_rec[6]);
});
update:
You should explicitly specify the target hostname on the client to connect to to avoid confusing the client on which address to connect to. There's also a cleaner way to specify a target port.
var socket = io.connect('http://localhost/', {
'port': 8080,
'transports': ['websockets']
});

Resources