Node.js client for a socket.io server - node.js

I have a socket.io server running and a matching webpage with a socket.io.js client. All works fine.
But, I am wondering if it is possible, on another machine, to run a separate node.js application which would act as a client and connect to the mentioned socket.io server?

That should be possible using Socket.IO-client: https://github.com/LearnBoost/socket.io-client

Adding in example for solution given earlier. By using socket.io-client https://github.com/socketio/socket.io-client
Client Side:
//client.js
var io = require('socket.io-client');
var socket = io.connect('http://localhost:3000', {reconnect: true});
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});
socket.emit('CH01', 'me', 'test msg');
Server Side :
//server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function (socket){
console.log('connection');
socket.on('CH01', function (from, msg) {
console.log('MSG', from, ' saying ', msg);
});
});
http.listen(3000, function () {
console.log('listening on *:3000');
});
Run :
Open 2 console and run node server.js and node client.js

After installing socket.io-client:
npm install socket.io-client
This is how the client code looks like:
var io = require('socket.io-client'),
socket = io.connect('http://localhost', {
port: 1337,
reconnect: true
});
socket.on('connect', function () { console.log("socket connected"); });
socket.emit('private message', { user: 'me', msg: 'whazzzup?' });
Thanks alessioalex.

const io = require('socket.io-client');
const socket_url = "http://localhost:8081";
let socket = io.connect(socket_url);
socket.on('connect', function () {
socket.emit("event_name", {});
});

Yes you can use any client as long as it is supported by socket.io. No matter whether its node, java, android or swift. All you have to do is install the client package of socket.io.

Client side code: I had a requirement where my nodejs webserver should work as both server as well as client, so i added below code when i need it as client, It should work fine, i am using it and working fine for me!!!
const socket = require('socket.io-client')('http://192.168.0.8:5000', {
reconnection: true,
reconnectionDelay: 10000
});
socket.on('connect', (data) => {
console.log('Connected to Socket');
});
socket.on('event_name', (data) => {
console.log("-----------------received event data from the socket io server");
});
//either 'io server disconnect' or 'io client disconnect'
socket.on('disconnect', (reason) => {
console.log("client disconnected");
if (reason === 'io server disconnect') {
// the disconnection was initiated by the server, you need to reconnect manually
console.log("server disconnected the client, trying to reconnect");
socket.connect();
}else{
console.log("trying to reconnect again with server");
}
// else the socket will automatically try to reconnect
});
socket.on('error', (error) => {
console.log(error);
});

something like this worked for me
const WebSocket = require('ws');
const ccStreamer = new WebSocket('wss://somthing.com');
ccStreamer.on('open', function open() {
var subRequest = {
"action": "SubAdd",
"subs": [""]
};
ccStreamer.send(JSON.stringify(subRequest));
});
ccStreamer.on('message', function incoming(data) {
console.log(data);
});

Related

Get data from NodeJS to Dart/Flutter using Socket.io

I'm trying to get data from the NodeJS and I've no idea how to do this can someone help me? The packages used in this example are: import 'dart:async' and import 'package:socket_io_client/socket_io_client.dart';
testSocket.dart
void testSocket(socket) async {
Socket socket;
try {
// Configure socket transports must be sepecified
socket = io('http://127.0.0.1:3000', <String, dynamic>{
'transports': ['websocket'],
});
// Connect to websocket
socket.connect();
// THIS IS WHERE I WANT TO PRINT THE DATA THAT WE GOT RECIEVED FROM NODEJS
socket.on('event', (data) => print(data));
}
print("connected: ${socket.connected}");
}
index.js
const server = require('http').createServer()
const io = require('socket.io')(server)
io.on('connection', function (client) {
client.on('event', function name(data) {
data = "test";
// Send data somehow to Flutter
io.on();
});
});
// The live server
var server_port = process.env.PORT || 3000;
server.listen(server_port, function (err) {
if (err) throw err
console.log('Listening on port %d', server_port);
});
I really appreciate it that you are taking time to help me out!
You have to emit events from your server and your client has to subscribe to those same events in order to receive data and updates.
testSocket.dart
void testSocket(socket) async {
Socket socket;
try {
socket = io('http://127.0.0.1:3000', <String, dynamic>{
'transports': ['websocket'],
});
socket.connect();
socket.on('testEvent', (data) => print(data));
}
print("connected: ${socket.connected}");
}
And your server has to then emit the testEvent with some data.
index.js
const server = require('http').createServer()
const io = require('socket.io')(server)
io.on('connection', function (client) {
client.on('event', function name(data) {
data = "test";
client.emit('testEvent', data);
});
});
var server_port = process.env.PORT || 3000;
server.listen(server_port, function (err) {
if (err) throw err
console.log('Listening on port %d', server_port);
});
Now since we're firing just a one-off event, the data will only come once. You'd have to emit the same event in order for the clients to receive updates.

Socket.io (emit, on) not working - Node JS

I am working on a node JS application, where I am trying to use socket.io following this tutorial. Until this tutorial everything is fine, even the client is connected to the server through the socket, as it display a message on connection. But I don't know why my code isn't working on emit, and on event, and event handler.
Below is my Code on server side :
const express = require("express");
const app = express();
const scrap = require("./algorithm");
const mysql = require("mysql");
const ms_connect = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'scrapper_db'
});
const server = app.listen(8000, function(){ console.log('Listening on 8000'); });
const io = require("socket.io").listen(server);
app.use(express.static(__dirname + "/"));
io.on("connection",function(socket){
console.log("Sockets Connection Made ! " + socket.id);
socket.emit("testing",{data:"I am tested"});
io.on("disconnect",function(){
console.log("Client Disconnected !");
})
})
//mySQL Conection
ms_connect.connect(function(err){
if(err) console.log(err);
ms_connect.query("Select * FROM test",function(err,rows,fields){
if(err) console.log("Error Executing Query");
})
})
app.get("/scrap",function(req,res){
res.sendFile(__dirname+"/index.html");
})
Client side code :
var socket = io.connect('http://localhost:8000/scrap');
console.log(socket.connected); //returns false :(
socket.on("testing", function(d) {
console.log(d);
});
In the client side, the socket.connected object returns false, but on server side it says connected. I don't know how , and
I am using third link from this socket.io cdnjs server.
You are doing io.connect('http://localhost:8000/scrap') but the scrap is not mentioned anywhere on the server side. It should be io.connect('http://localhost:8000/'). Pointing to your HTML file is not needed because the socket.io server and your webserver are unrelated.
Also as pointed out by #TommyBs you should use
socket.on('connect', () => { console.log(socket.connected); });
to check if you are connected because connecting is asynchronous so it will not have connected yet by the time you do console.log(socket.connected);
The whole client code would be
var socket = io.connect('http://localhost:8000');
socket.on('connect', () => { console.log(socket.connected); });
socket.on("testing", function(d) {
console.log(d);
});
Change http://localhost:8000/scrap to http://localhost:8000/ in the client code. You're connecting to the wrong route.

Why Client says CONNECTED whereas the SERVER does not say so in NODE JS?

Details Regarding SERVER and CLIENT.
socket.io on server side (NODEJS)
socket.io-client on client side (also in NODEJS)
Nothing is logged on the SERVER side, as the server never lets the client connect to itself.
Whereas on the CLIENT side I see this output:
'I HAVE CONNECTED.'
SERVER CODE:
var io = require('socket.io')(server);
io.use(function(socket, next){
if (socket.handshake.query.user === "admin") {
console.log("CALLED BEFORE CONNECTION........ :)");
return next();
}
return next(new Error('Authentication error'));
});
io.on('connection', function(socket) {
console.log('CLIENT HAS CONNECTED.');
});
CLIENT CODE:
var io = require('socket.io-client');
var socket = io.connect('http://localhost:5000', { query: "user=admin11" });
socket.on('connect', function (socket) {
console.log('I HAVE CONNECTED.');
});

Socket.io-client does not receive any messages after successful connection

I have a working socket.io server up and running, and i am trying to implement a server side socket.io client. Below is the code snippet i have been using for testing. The problem with this is that the client outputs the message only once, in this case it receives 'Welcome' only. I have tried sending messages to the private channel, 'message' via browser but it doesn't show any output even though the server can receive and emit the message successfully.
Client
var io = require('socket.io-client');
var socket = io.connect('http://localhost:3000', {'force new connection': true});
socket.on('connect', function(){
socket.on('message', function (data) {
console.log(data);
});
});
Server
var io = require('socket.io').listen(server);
var i=0;
io.sockets.on('connection', function (socket) {
socket.emit('message', { 'msg': 'Welcome'});
socket.on('message', function (from, msg) {
socket.emit('message', { 'msg': 'Hello World - ' + i });
i++;
});
});
Have you tried doing this?
console.log(data.msg);
Can you try changing "socket" to "this":
this.emit('message', { 'msg': 'Hello World - ' + i });
You should emit from client side to server. So server can send the data back to client. I guess this code works fine :-)
Client
var io = require('socket.io-client');
var socket = io.connect('http://localhost:3000', {'force new connection': true});
socket.on('connect', function(){
socket.on('messageRecieved', function (data) {
console.log(data);
});
socket.emit('message','some message');
});
Server
var io = require('socket.io').listen(server);
var i=0;
io.sockets.on('connection', function (socket) {
socket.on('message', function (msg) {
console.log(msg);
socket.emit('messageRecieved', { 'msg': 'Hello World - ' + i });
i++;
});
});

How to connect two node.js servers with websockets?

Here's my problem:
I have server A, running node.js and using socket.io for communicating with clients (web browsers). This all is running fine and dandy.
However, now that I have server B, which also needs to connect to server A through websockets, I have hit a wall. None of the node.js websocket clients I've found won't work with the socket.io on the server A.
So, this is the case I'm striving for:
.--------. .----------. .----------.
| CLIENT | <--> | SERVER A | <--> | SERVER B |
'--------' '----------' '----------'
Client-server A connection is done through socket.io
Now, Server B (running node.js) should connect to server A via websocket (in order to go through port 80). But...
Even the example code in socket.io-client module doesn't work... :/
// Connect to server
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected.');
});
The code just passes without any errors and execution ends after few seconds.
Update: Code samples
Server (which works just fine) looks like this:
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Client looks like this
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = new io.Socket('localhost', {port: 8080});
socket.connect();
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
1, 2 and 3 prints out just fine, no errors, and few seconds later the process just exits
Also, server A doesn't output anything to the log, even though I have the socket.io logging set on "everything".
For future people:
Here is 2 very simple Node.js apps that use socket.io to connect, send and receive messages between each other.
Required package is:
npm install socket.io
Node-App-1 server.js:
var io = require('socket.io').listen(3000);
io.on('connection', function (socket) {
console.log('connected:', socket.client.id);
socket.on('serverEvent', function (data) {
console.log('new message from client:', data);
});
setInterval(function () {
socket.emit('clientEvent', Math.random());
console.log('message sent to the clients');
}, 3000);
});
Node-App-2 client.js:
var io = require('socket.io-client');
var socket = io.connect("http://localhost:3000/", {
reconnection: true
});
socket.on('connect', function () {
console.log('connected to localhost:3000');
socket.on('clientEvent', function (data) {
console.log('message from the server:', data);
socket.emit('serverEvent', "thanks server! for sending '" + data + "'");
});
});
Turns out I was using old examples, for some reason, even though I triple checked them. Well, doh.
Also, it turned out that the socket.io-client is broken on latest Node (6.x.x). Managed to find an update from github for it, replaced the files and yay, everything's working!
Edit: Unfortunately I didn't save any links to working examples but after quickly skimming through the code it seems that the only changes were to the client code, which now looks like this:
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = io.connect('localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
Here is a snippet of code I wrote, it's using socket.io 1.0.6 and socket.io-client 1.0.6. The case is the following:
Server A (Socket.io Client) <---> Server B (Socket.io Server)
Server B (Server):
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res)
{
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket)
{
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Server A (Client):
console.log('1');
// Connect to server
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
If I'm using localhost:8080 only on the client server it doesn't connect.

Resources