next.js socket.io useeffect not updating on socket message - sockets

i'm facing an issue with my socket client on next.js . i have created a context for providing my socket instance for all components in the application , the problem is that when i want to use the socket context on my component i am using the useeffect hook be called once the socket is changed and i will handle on message call ( like any tutorial i have seen on the web ) but with new message on the socket the useeffect is not called at all . for those who may think this is context issue i should say its not i have tested socket initiation on the component itslef and still useeffect not being called .
here is the way im using the socket instance :
export default function MyComp(props){
const cookies = new Cookies()
const token = cookies.get('token');
const socket = io(routes.socket_url, { path: '/socket',
transports: ['websocket'],
query:{
token,
user_id:'someuserid'
}
});
useEffect(() => {
console.log('socket changed');
console.log(socket);
console.log('socket changed');
},[socket])
}
i can actually see the connection on my devtools and also see the message in the network tab so it means we have a connection (also checked on server ) but the console.log() part is never called on new messages .
and here is my component using the context .
export default function MyComp(props){
const socket = useContext(SocketContext);
useEffect(() => {
console.log('socket changed');
console.log(socket);
console.log('socket changed');
},[socket])
}
the connection in this one is also available in the devtools and it gets the new message on networks tab but the logging is never called in useeffect .
thank you for any help .

guys i found the answer . i was using socket.io-client v 3.1.1 and i started testing other versions . for some strange reason
in version 3 socket instance is not receiving any messages though the connection is already stablished and i can see the messages coming in the networks tab .
anyways i changed version from 3 to 2.1.1 and its working like a charm .

Related

XMPPJS use xmpp in another js file?

I want send message to my XMPP server with my strapi API.
My connection to the XMPP is in index.js (and I can send messages here) and I want to send message from my controller is it possible ?
|index.js
|carrefour/
---|controllers/
---|carrefour.js
In index.js I have
module.exports = {
register(/*{ strapi }*/) {},
bootstrap(/*{ strapi }*/) {},
}
But if I add function or my xmpp object
[2022-10-11 16:54:05.824] error: Invalid file `./src/index.js`: this field has unspecified keys: myfunction
Thanks
I found an solution.
I created a new JS in which I make my connection to the XMPP and then I export the xmpp variable

how can I make Flutter graphql subscription work with ferry package?

I have a graphql api with apollo-server. I tested all queries, mutations and subscriptions with Graphql Playground.
I am developing the client app in Flutter using Ferry package as grapqhl client. All queries and mutations work fine, but subscriptions don't.
When sending a subscription request the websocket connection is established, however the subscription is not started. I tested the subscription on the Graphql Playground and the connection request messages looks like this
Graphql Playground network panel
but with ferry client it get stuck on connection_init
Flutter Web app network panel
var link = WebSocketLink(
"ws://localhost:4000/graphql",
initialPayload: {"subscriptionParam": arg},
);
var client = Client(link: link);
client.request(request).listen((data) {//request is an object from autogenerated class from ferry
log(data.toString());//never gets here
}, onError: (error, stack) {
log("Subscription error: " + error.toString());
});
What is wrong in my code? Help please!
So guys I solved my problem, the issue was related to link not sending Sec-WebSocket-Protocol:graphql-ws on connection request headers. So I change the link initialization to:
final link = WebSocketLink(
null, //Global.graphqlWsServerUrl,
autoReconnect: true,
reconnectInterval: Duration(seconds: 1),
initialPayload: {"subscriptionParam": arg},
channelGenerator: () => WebSocketChannel.connect(Uri.parse(Global.graphqlWsServerUrl), protocols: ['graphql-ws']),
);

IOWebSocketChannel detect when the connection is open

I'm new to dart/flutter. I'm trying to use WebSocketChannel to connect to a websocket server.
Is there a way to detect when the connection with server is completed?
What I want to do is to send some messages the moment the connection with server is completed.
In javascript implementation this was something done like this:
exampleSocket.onopen = function (event) {
exampleSocket.send("Here's some text that the server is urgently awaiting!");
};
Is there an alternative on dart/flutter ? Is it possible to use it with WebSocketChannel
The WebSocket
class static method connect
returns a Future that resolve to a web socket when the connection is established.
If you want to send a message when the connection is up something like that should work:
import 'dart:io';
import 'package:web_socket_channel/io.dart';
WebSocket.connect("ws://a.b.c.d").then((ws) {
// create the stream channel
var channel = IOWebSocketChannel(ws);
channel.sink.add("hello");
})
The package web_socket_channel must be added to pubspec.yaml dependencies.

MQTT connection creation and subscribe

I'm setting up a new mqtt conection in my app but there is a problem when i would like to create the main connection of mqtt.
I'm using mqtt.js.
I've tried all what is done in MQTT documentation but nothing happens..
mqttFunction(){
var mqtt = require('mqtt');
var client = mqtt.connect([{host: 'localhost', port: '1883'},]);
client.subscribe('presence')
client.on('message', function (topic, message) {
console.log(message);
});
}
I expect the output of the mqtt broker to be 'ON' when i asked it to respond.
The error is: ERROR ReferenceError: process is not defined
The documentation you followed is intended for Node.js and various other back-end JavaScript frameworks. Even though it uses NPM, Ionic ultimately produces a front-end framework, and its applications run a bit differently.
For example, Ionic programs may not have a global process variable like Node.js. mqtt.js expects this variable, with code like:
if (commist.parse(process.argv.slice(2)) !== null){...}
You could declare a process object, and get past this particular error. Other obstacles could come up.
var process = {env : {NODE_ENV: 'production'}}
If there are still issues with that, you could try the instructions for browser usage, which point to a specially compiled version, like https://unpkg.com/mqtt#3.0.0/dist/mqtt.min.js. I have had less luck with mqtt.js in the browser, and you may want an alternative like web-mqtt-cient / Paho if more complex connections are involved.

What's Socket.IO sending and getting data (acknowledgements)?

This example from Socket.IO website is confusing me. Sending and getting data (acknowledgements):
Client:
<script>
socket.on('connect', function () {
socket.emit('ferret', 'tobi', function (data) {
console.log(data); // data will be 'woot'
});
});
</script>
Server:
io.sockets.on('connection', function (socket) {
socket.on('ferret', function (name, fn) {
fn('woot');
});
});
I'm actually reproducing this example. What I can't understand is:
Q1: How does this work in the first place. Does the server (when executing fn) automagically emits the result to the client? Does Socket.IO bind fn to the client third parameter of emit?
Q2: What's the (unused) name parameter in server anonymous function (name, fn)? Logging it shows that it's undefined, why?
Found by myself, correct me if I'm wrong:
name (what unlucky name from the official documentation!!!) is actually the data sent by the client.
fn corresponds to the 3th parameter of client code, and when executed (from the server) automagically (?) sends the data back to the client. Amazing!
Indeed; it gets a lot clearer if you rename "fn" to "callback", as seen here: Acknowledgment for socket.io custom event. That callback is never executed on the server side; the server simply sends the data passed to the callback (in this case, the string "woot") back to the client as an acknowledgement. The callback is then executed on the client using the data sent by the server.
To send data from client to server
socket.emit("Idofhtmltag",value);
To receive data from server, on client html add this
socket.io("Idofhtmltag",function(msg){ }) ;