When I try to connect to my nodejs server it is showing me this error-
connect_error: [{"cause":{"detailMessage":"Control frames must be final.","stackTrace":[],"suppressedExceptions":[]},"detailMessage":"websocket error","stackTrace":[],"suppressedExceptions":[]}]
I used flutter_socket_io for socket connection
My flutter code
socketIO = SocketIOManager().createSocketIO(
websocketUrl, '/', socketStatusCallback: (status) {
print("web socket -------------status");
print(status);
if (status.toString() == "connect") {
print("connected to server with websocket------------------------");
// socketIO.sendMessage("socket request", jsonEncode({"id": id}));
}
});
socketIO.init();
socketIO.connect().then((value){
print('socket connect');
});
Related
I would like to avoid using the package web_socket_channel which despite its vote doesn't seem to not be actively maintained (many github issues not answered) and doesn't handle errors.
I simply need to connect from Flutter to my WebSocket API in AWS.
How can i do that with dart:io package ? Or is it possible with socket_io_client ? I see that the connection is with http and not wss.
I have found a way in addition to the usual try - catch to handle error in the channel.sink.listen StreamSubscription object with the web_socket_channel package.
You can do the following according to this answer :
_channel = IOWebSocketChannel.connect(
'ws://yourserver.com:port',
);
///
/// Start listening to new notifications / messages
///
_channel.stream.listen(
(dynamic message) {
debugPrint('message $message');
},
onDone: () {
debugPrint('ws channel closed');
},
onError: (error) {
debugPrint('ws error $error');
},
);
This actually works and there is no need to use SocketIO in my use case of course.
I recommend you to use this multiplatform websocket package https://pub.dev/packages/websocket_universal . There you can even use low-level webSocket interactions.
Complete example:
import 'package:websocket_universal/websocket_universal.dart';
/// Example works with Postman Echo server
void main() async {
/// Postman echo ws server (you can use your own server URI)
/// 'wss://ws.postman-echo.com/raw'
/// For local server it could look like 'ws://127.0.0.1:42627/websocket'
const websocketConnectionUri = 'wss://ws.postman-echo.com/raw';
const textMessageToServer = 'Hello server!';
const connectionOptions = SocketConnectionOptions(
pingIntervalMs: 3000, // send Ping message every 3000 ms
timeoutConnectionMs: 4000, // connection fail timeout after 4000 ms
/// see ping/pong messages in [logEventStream] stream
skipPingMessages: false,
/// Set this attribute to `true` if do not need any ping/pong
/// messages and ping measurement. Default is `false`
pingRestrictionForce: false,
);
/// Example with simple text messages exchanges with server
/// (not recommended for applications)
/// [<String, String>] generic types mean that we receive [String] messages
/// after deserialization and send [String] messages to server.
final IMessageProcessor<String, String> textSocketProcessor =
SocketSimpleTextProcessor();
final textSocketHandler = IWebSocketHandler<String, String>.createClient(
websocketConnectionUri, // Postman echo ws server
textSocketProcessor,
connectionOptions: connectionOptions,
);
// Listening to webSocket status changes
textSocketHandler.socketHandlerStateStream.listen((stateEvent) {
// ignore: avoid_print
print('> status changed to ${stateEvent.status}');
});
// Listening to server responses:
textSocketHandler.incomingMessagesStream.listen((inMsg) {
// ignore: avoid_print
print('> webSocket got text message from server: "$inMsg" '
'[ping: ${textSocketHandler.pingDelayMs}]');
});
// Listening to debug events inside webSocket
textSocketHandler.logEventStream.listen((debugEvent) {
// ignore: avoid_print
print('> debug event: ${debugEvent.socketLogEventType}'
' [ping=${debugEvent.pingMs} ms]. Debug message=${debugEvent.message}');
});
// Listening to outgoing messages:
textSocketHandler.outgoingMessagesStream.listen((inMsg) {
// ignore: avoid_print
print('> webSocket sent text message to server: "$inMsg" '
'[ping: ${textSocketHandler.pingDelayMs}]');
});
// Connecting to server:
final isTextSocketConnected = await textSocketHandler.connect();
if (!isTextSocketConnected) {
// ignore: avoid_print
print('Connection to [$websocketConnectionUri] failed for some reason!');
return;
}
textSocketHandler.sendMessage(textMessageToServer);
await Future<void>.delayed(const Duration(seconds: 30));
// Disconnecting from server:
await textSocketHandler.disconnect('manual disconnect');
// Disposing webSocket:
textSocketHandler.close();
}
I'm trying to add socket io to a flutter project. I'm using socket_io_client 2.0.0-beta.4-nullsafety.0 but when I try to connect to server's socket it just refuse the connection and throw a timeout error.
Here's the code im using:
_connectSocket() {
Socket socket = io('SERVER IP',
OptionBuilder()
.enableAutoConnect()
.build()
);
socket.onConnecting((data) => print("conecting socket..."));
socket.onConnectError((data) => print("error : "+data.toString()));
socket.onConnectTimeout((data) => print(data.toString()));
}
Has anyone been through this?
Thanks in advance
socket = IO.io("ip sever",<String, dynamic>{
"transports": ["websocket"],
"autoConnect": false,
'extraHeaders': {'foo': 'bar'},
}); socket.connect();
// socket = await IO.io('ip server',
// OptionBuilder()
// .setTransports(['websocket']).build());
socket.onConnect((_) => print('connect'));
socket.onConnect((_) {
print('connect');
});
socket.onConnectError((data) => print( 'error : '+ data.toString() ));
I have a super simple socket.io node server like below
// Socket!
io.on("connection", (socket) => {
console.log("a user connected");
socket.on("msg", (aaa) => {
console.log(aaa);
});
socket.on("fromServer", (_) => print(_));
console.log(socket.handshake.query)
});
And, here is my Flutter code to connect to the server
// Dart client
IO.Socket socket = IO.io(
'http://192.168.219.102:7199',
IO.OptionBuilder()
.setTransports(['polling'])
.disableAutoConnect()
.setQuery({"hee": 'asdf'})
.build());
socket.connect();
socket.onConnect((_) {
print(_);
});
On the network tab, I see two requests
101 HTTP 490ms
101 WS Pending
When I connect to the socket.io server from the other node.js server, I see the console.log of a user connected on the terminal. However, I see nothing from Flutter.
What can I do to receive the socket message on the server and connect the device.
I implemented fiebase messaging in my flutter application. I am trying to catch it's connection error for example something like this:
6.26.0 - [Firebase/Messaging][I-FCM002025] Failed to connect to direct channel, error: Error Domain=com.google.fcm Code=4 "No internet available, cannot connect to FIRMessaging" UserInfo={NSLocalizedFailureReason=No internet available, cannot connect to FIRMessaging}
but there is no place to catch it. How can i catch firebase messaging connection?
final FirebaseMessaging _fcm = FirebaseMessaging();
_fcm.getToken().then((value) {
_token = value;
print("Message token is: $_token");
}, onError: (err) {
print("getToken onError is: $err");
}).catchError((onError) {
print("getToken catchError is: $onError");
});
I am having trouble connecting to the LiveQuery server that I setup on the server side of my React Native project. I followed the instructions on the site verbatim, but can only manage to get 'error on socket' when I connect with numerous attempts by the server to reconnect.
Here is my server setup:
liveQuery: {
classNames: ['BekonRequest'],
}
var port = 1337;
server.listen(port, function() {
console.log('parse-server running on port ' + port); });
var parseLiveQueryServer = ParseServer.createLiveQueryServer(server);
server.listen(port, function() {
console.log('parse-server running on port ' + port);
});
var parseLiveQueryServer = ParseServer.createLiveQueryServer(server);
And my client side code:
let requestQuery = new Parse.Query('BekonRequest');
requestQuery.equalTo("username", "broncos#nfl.com");
let subscription = requestQuery.subscribe();
subscription.on('create', (requests) => {
console.log(requests);
});
Can anyone see why I am not able to connect successfully?