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

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.

Related

Flutter Socket io disconnects after some seconds

Am using a local socket server using express which is expose to the internet using ngrok. This is the server code:
const app = require('express')();
const http = require('http').createServer(app);
app.get('/', (req, res) => {
res.send("Node Server is running. Yay!!");
});
//Socket Logic
const socketio = require('socket.io')(http)
socketio.on("connection", (userSocket) => {
console.log('Connected to socket');
});
http.listen(3000, () => {
console.log('listening on port 3000');
});
and my connection logic is:
void connectToServer() {
try {
socket = io('https://fa6387728fcd.ngrok.io', <String, dynamic>{
'transports': ['websocket'],
'autoConnect': false,
});
// Connect to websocket
socket.connect();
// Handle socket events
socket.on('connect', (data) => print('Connected to socket server'));
socket.on('disconnect', (reason) => print('disconnected $reason'));
socket.on('error', (err) => print('Error: $err'));
} catch (e) {
print(e.toString());
}
}
But i keep getting disconnected ping timeout or sometimes i get disconnected transport close
I had the same problem.
The problem wasn't caused by the socket_io_client package.
When i update socket.io on my server side, the problem is solved.
Just run npm install socket.io#latest command on your node.js server.
According to the socket_io_client official doc, use this workaround if you are using https server:
class MyHttpOverrides extends HttpOverrides {
#override
HttpClient createHttpClient(SecurityContext context) {
return super.createHttpClient(context)
..badCertificateCallback =
(X509Certificate cert, String host, int port) => true;
}
}
void main() {
HttpOverrides.global = new MyHttpOverrides();
runApp(MaterialApp(
...
));
}

How can i receive emit response within laravel

I am using socket.io and node.js for a socket connection, I am sending data via API to a socket using below laravel code.
its working perfect after all procedure in a socket.js file which is running in a terminal with node socket.js. I just want a response on the same function where I publish the event, is it possible with this or I need to do something else.
Note: everything is perfect just need a response in the same function where I publish
Thanks
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use App\Http\Requests;
use LRedis;
class MessageController extends Controller{
public function store(Request $request){
$data = [
'id'=>1,
'game_name'=>'PUB',
];
$redis = LRedis::connection();
$redis->publish('message', json_encode($data));
}
}
////// node node.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(3000, function () {
console.log('Listening on Port 3000');
});
redisClient.subscribe('message');
redisClient.on("message", function (channel, data) {
const dataj = JSON.parse(data);
console.log(data);
///// send data to client which is connected with me
io.emit("eventsend", {
"id": dataj.id,
"game": dataj.game,
});
});
io.on('connection', function (socket) {
/////////////////////// send by client
socket.on("eventrec", function (data) {
console.log(data);
});
//console.log("Connected!");
/////////////////////// send by client
socket.on("success_repo", function (data) {
////////// i want this response in my laravel file where i publish the message event
console.log(data);
});
socket.on('disconnect', function () {
redisClient.unsubscribe('message');
});
});

uWebSockets - push events to server

I have a uWebSockets server as it seems to be a lot more performance friendly than socket.io servers.
So I have a server and its connected fine and after some trouble I got the index.html client side to connect, but now I'm not able to push events to the server from the client side. What am I doing wrong?
var WebSocketServer = require('uws').Server,
express = require('express'),
path = require('path'),
app = express(),
server = require('http').createServer(),
createEngine = require('node-twig').createEngine;
var wss = new WebSocketServer({server: server});
wss.on('connection', function (ws) {
ws.on('join', function (value) {
console.log('SOMEONE JUST JOINED');
});
ws.on('close', function () {
//console.log('stopping client interval');
clearInterval(id);
});
});
server.on('request', app);
server.listen(8080, function () {
console.log('Listening on http://localhost:8080');
});
index.html
<script>
var host = window.document.location.host.replace(/:.*/, '');
var server = new WebSocket('ws://' + host + ':8080');
server.onmessage = function (event) {
updateStats(JSON.parse(event.data));
};
server.onopen = function (event) {
server.send("Here's some text that the server is urgently awaiting!");
server.send('join');
};
function something() {
console.log('WORKED');
server.send('join');
}
</script>
You don't have an event listener setup on the server side that does receive and react on the message. Like
ws.on('message', function (msg) {
// Do something with the message received from the client
});

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++;
});
});

Node.js client for a socket.io server

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);
});

Resources