rikulo / socket.io-client-dart Goto Github PK
View Code? Open in Web Editor NEWsocket.io-client-dart: Dartlang port of socket.io-client https://github.com/socketio/socket.io-client
Home Page: https://quire.io
License: MIT License
socket.io-client-dart: Dartlang port of socket.io-client https://github.com/socketio/socket.io-client
Home Page: https://quire.io
License: MIT License
Hello,
First off, I want to thank all the contributers for the great API. I am new on the flutter side, and I saw that this library offers support for flutter so I wanted to try it out. However, I am not able to get any action from the library. It doesn't throw any errors, it doesn't get connected. It is purely idle.
I'm trying to run this on an actual android device.
Flutter doctor output:
[✓] Flutter (Channel stable, v1.2.1, on Mac OS X 10.14.2 18C54,
locale en-US)
[✓] Android toolchain - develop for Android devices (Android SDK
version 28.0.3)
[✓] iOS toolchain - develop for iOS devices (Xcode 10.1)
[!] Android Studio (version 3.3)
✗ Flutter plugin not installed; this adds Flutter specific
functionality.
✗ Dart plugin not installed; this adds Dart specific
functionality.
[✓] VS Code (version 1.33.1)
[✓] Connected device (1 available)
class SocketClientAPI {
final String _base;
final String _path;
IO.Socket _socket;
SocketClientAPI(this._base, this._path);
Future<bool> handshake(String token) async {
Completer<bool> isConnected = Completer<bool>();
Map opts = Map<dynamic, dynamic>();
opts['forceNew'] = true;
opts['autoConnect'] = true;
opts['query'] = {
'accessToken': token,
};
_socket = IO.io(_base + _path, opts);
_socket.on('connect', (_) {
print('connect');
print('id: ' + _socket.id);
_socket.emit('save', 'test');
isConnected.complete(true);
});
_socket.on('message_saved', (data) => print(data));
_socket.on('disconnect', (_) => print('disconnect'));
_socket.on('fromServer', (_) => print(_));
_socket.on('error', (error) {
print('error');
print(error);
isConnected.complete(false);
});
_socket.open();
print('Conn: ' + _socket.connected.toString());
print('Disc: ' + _socket.disconnected.toString());
return isConnected.future;
}
}
This is the final version of options as I traced from the manager.
{
forceNew:true,
autoConnect:true,
query:{
accessToken: "token"
},
path: "/socket.io",
hostname: "192.168.1.62",
secure:false,
port:3000
}
Thanks in advance,
Kagan
On android when I discounted event "connect" call normal but on IOS event "connect" doesn't fire.
how to get callback with acknowledgment from the server after emit, for example??
class SocketChatClientManager {
static final SocketChatClientManager _singleton = new SocketChatClientManager._private();
static Function(dynamic) onMessage;
static SocketChatClientManager getInstance() => _singleton;
IO.Socket socket;
SocketChatClientManager._private(){
// print("RocketChatClient._private");
//initWebSocket();
//initSocketChatClientManager();
}
connectAndJoinRoom(room,username){
if(socket != null){
close();
}
try {
socket = IO.io('http://$MHost:$MPort',<String, dynamic>{
'transports': ['websocket'],
'extraHeaders': {'token': UserManager.currentUser.token} // optional
});
print('-->http://$MHost:$MPort');
socket.on('connect', (_) {
print('connect');
joinRoom(room, username);
});
socket.on('disconnect', (_){
print('disconnect');
leaveRoom(room);
});
socket.on('room chat message',(data){
if(onMessage!=null){
onMessage(data);
}
});
} catch (e) {
print(e);
}
}
leaveRoom(room){
if(socket.connected){
print("leave");
socket.emit('leave',{"room":room});
}
}
joinRoom(room,username){
if(socket.connected){
print("join");
socket.emit('join',{"room":room,"user":{"name":username}});
}
}
sendToRoom(room,message){
if(socket.connected){
socket.emit('room chat message',{"room":room,"msg":message});
}
}
close(){
try {
socket.disconnect();
socket.close();
socket.destroy();
socket=null;
print('SOCKET DISCONNECTED');
} catch (e) {
print(e);
}
}
}
But close socket and reconnet is not work!
@override
void initState() {
super.initState();
print("widget.room.channel ---> ${widget.room.channel}");
SocketChatClientManager.getInstance().connectAndJoinRoom(widget.room.channel,UserManager.currentUser.nickname);
SocketChatClientManager.onMessage = (data){
print("data:$data");
if(mounted){
setState(() {
messages.add(data);
});
}
};
}
I've got the socket working when I have my client files running on pub serve through Webstorm. (Although the connection is sometimes finnicky.)
But when I do a pub build so that I can serve up the files from my server, the socket doesn't seem to work at all.
Here's my (relevant) dart client code:
void ngOnInit() {
name = _routeParams.get('name');
socket = IO.io('http://localhost:3000');
socket.connect();
socket.on('connect', (_) {
print('Socket connected (client)');
// need to send something stupid initially so that it will keep listening
socket.emit('client', 1);
socket.on('server', (_) => print('handshake'));
countDownTimer = new Timer.periodic(const Duration(seconds: 1), (Timer countDownTimer) {
countDown--;
timerMsg = countDown > 0 ? 'BEGIN IN ${countDown}' : 'GO!';
if (countDown == 0) {
socket.emit('start game', 2);
countDownTimer.cancel();
gameInProgress = true;
gameTimer = new Timer.periodic(const Duration(seconds: 1), (Timer gameTimer) {
gameTime--;
gameTimerMsg = gameTime > 0 ? gameTime.toString() : 'END GAME';
if (gameTime == 0) {
print('game over');
print('updateLeaderboard');
Leader player = new Leader(name, 25);
_leaderboardService.leaders.add(player);
_leaderboardService.leaders.sort((a, b) => b.score.compareTo(a.score));
print('about to end game');
socket.emit('end game', 'i am a string');
print('should have ended game');
gameTimer.cancel();
this._router.navigate(['Leaderboard', player.toMap()]);
}
});
}
});
});
socket.on('new color', (data) {
print('new color: $data');
HTML.Animation animation;
HTML.Element element;
switch (data) {
case 1:
element = green.nativeElement; break;
case 2:
element = red.nativeElement; break;
case 3:
element = yellow.nativeElement; break;
case 4:
element = blue.nativeElement; break;
}
animation = element.animate([{"opacity": 100}, {"opacity": 0}], 150);
animation.play();
});
socket.on('point', (_) => score++);
socket.on('ended game', (_) {
socket.clearListeners();
socket.disconnect();
});
socket.on('disconnected', (_) => print('socket disconnected (server)'));
}
The library only works when you use transporting over websocket. By default the library send the connection request over http (long polling) and you can see it on the access log of the server but never switch to websocket.
We are using socket io version 2.0.4 on our server.
172.31.3.14 - - [20/Aug/2019:08:12:06 -0500] "GET /socket.io/?EIO=3&transport=polling&t=Mol9v3G&sid=c40FSVz-gs98xm1iAALE HTTP/1.1" 200 3 "http://stagingiris.1doc3.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36" "201.217.201.157"
Hi,
Do you mind updating the dependency to UUID from 1.0.3 to 2.0.0?
I have version conflicts with packages that use UUID 2.0.0.
EDIT: for clarification, I'm talking about socket_io_common 0.9.0+2
Can anyone provide steps by which I can implement a socket in my project?
When I am cloning this project it's working fine but I would like to use socket in my own project and i am facing issues with connecting the socket, Actually, I am not getting how to use socket exactly.
socket = IO.io("myserverurl", <String, dynamic>{
'transports': ['websocket']
});
socket.nsp = "/chats";
socket.on("receiveMessage", (data) {
print("from socket $data");
});
socket.connect();
socket.emit("join", {"Id": "id"});
i send message my server log message call twice why it is called twice?
server code
io.of('nsp').to('id').('receiveMessage',message);
Is it more important to stay true to the JavaScript style of the library or should this port take into account the standard Dart style which is less error-prone than checking String
s? For example ,
socket.on('connect', (_) {});
would be
socket.onConnect((_) {});
etc
as title.
I'm working to implement this and utilize it with flutter_web. Is there something specific that needs to be done to support?
I tried to add it to the packet in socket.dart lines 157 - 163
var packet = {
'type': binary ? BINARY_EVENT : EVENT,
'data': sendData,
'options': {
'Access-Control-Allow-Origin: *',
'compress': this.flags?.isNotEmpty == true && this.flags['compress']
}
};
Dear Author,
Firstly, thanks for this package I have been using it over the past month and it has been working very well in my flutter app.
However, today I upgraded my libraries including this library from 0.9.1 to 0.9.3 and suddenly it won't connect to the node js websocket anymore.
After some testing I found out that when reverting to 0.9.1 everything still works but in 0.9.2 and 0.9.3 it doesn't anymore.
Not sure if this is important, but to get this library to work I had to set the transports to websocket only, for some reason polling and then upgrading was not working correctly (even though the web version of my app can use it).
I feel that this repository should be more popular and be the de facto solution when building a socket.io application in dart, especially with Flutter.
Because of this issue, other repositories that are only an abstraction over socket.io-java and socket.io-swift are gaining more traction even though this package should be used instead.
I think it is explained by the bad scoring of this package on pub.dev which impact a lot on search ranking (link here). We should do something about it, because I feel that this package is really well made.
how to create a secure connection with https
EDIT: solved now, check my answers below
I am trying to use this lib but it doesn't seem to work
I tried with a really simple example like this:
import 'package:socket_io_client/socket_io_client.dart' as IO;
main(List<String> arguments) {
Logger.root.level = Level.ALL;
Logger.root.onRecord.listen((record) {
print('${record.level.name}: ${record.time}: ${record.message}');
});
IO.Socket _socket = IO.io("http://192.168.8.100:4040", <String, dynamic>{
'transports': ['websocket']
});
_socket.emitWithAck("authenticate", {"strategy":"local", "email":"[email protected]", "password":"test69"}, ack: (result){
print("Return res: $result");
List jsar = json.decode(result);
if (jsar.length == 1) { //returned an error message
print("Authentication error");
}
else {
String jsdata = jsar[1] ?? "";
print("Authentication data: $jsdata");
}
});
}
but it is throwing an error. Here is the exception call stack:
Object.noSuchMethod (dart:core-patch/object_patch.dart:51)
Function._apply (dart:core-patch/function_patch.dart:10)
Function.apply (dart:core-patch/function_patch.dart:31)
Socket.onack (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_client-0.9.5\lib\src\socket.dart:323)
Socket.onpacket (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_client-0.9.5\lib\src\socket.dart:248)
EventEmitter.emit. (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_common-0.9.0+5\lib\src\util\event_emitter.dart:52)
List.forEach (dart:core-patch/growable_array.dart:283)
EventEmitter.emit (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_common-0.9.0+5\lib\src\util\event_emitter.dart:51)
Manager.ondecoded (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_client-0.9.5\lib\src\manager.dart:321)
EventEmitter.emit. (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_common-0.9.0+5\lib\src\util\event_emitter.dart:52)
List.forEach (dart:core-patch/growable_array.dart:283)
EventEmitter.emit (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_common-0.9.0+5\lib\src\util\event_emitter.dart:51)
Decoder.add (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_common-0.9.0+5\lib\src\parser\parser.dart:159)
Manager.ondata (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_client-0.9.5\lib\src\manager.dart:312)
EventEmitter.emit. (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_common-0.9.0+5\lib\src\util\event_emitter.dart:52)
List.forEach (dart:core-patch/growable_array.dart:283)
EventEmitter.emit (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_common-0.9.0+5\lib\src\util\event_emitter.dart:51)
Socket.onPacket (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_client-0.9.5\lib\src\engine\socket.dart:484)
Socket.setTransport. (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_client-0.9.5\lib\src\engine\socket.dart:306)
EventEmitter.emit. (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_common-0.9.0+5\lib\src\util\event_emitter.dart:52)
List.forEach (dart:core-patch/growable_array.dart:283)
EventEmitter.emit (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_common-0.9.0+5\lib\src\util\event_emitter.dart:51)
Transport.onPacket (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_client-0.9.5\lib\src\engine\transport\transport.dart:135)
Transport.onData (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_client-0.9.5\lib\src\engine\transport\transport.dart:128)
IOWebSocketTransport.addEventListeners. (c:\Development\Flutter\SDK.pub-cache\hosted\pub.dartlang.org\socket_io_client-0.9.5\lib\src\engine\transport\io_websocket_transport.dart:64)
_RootZone.runUnaryGuarded (dart:async/zone.dart:1314)
_BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:336)
_BufferingStreamSubscription._add (dart:async/stream_impl.dart:263)
_SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:764)
_StreamController._add (dart:async/stream_controller.dart:640)
_StreamController.add (dart:async/stream_controller.dart:586)
new _WebSocketImpl._fromSocket. (dart:_http/websocket_impl.dart:1141)
_RootZone.runUnaryGuarded (dart:async/zone.dart:1314)
_BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:336)
_BufferingStreamSubscription._add (dart:async/stream_impl.dart:263)
_SinkTransformerStreamSubscription._add (dart:async/stream_transformers.dart:68)
_EventSinkWrapper.add (dart:async/stream_transformers.dart:15)
_WebSocketProtocolTransformer._messageFrameEnd (dart:_http/websocket_impl.dart:334)
_WebSocketProtocolTransformer.add (dart:_http/websocket_impl.dart:229)
_SinkTransformerStreamSubscription._handleData (dart:async/stream_transformers.dart:120)
_RootZone.runUnaryGuarded (dart:async/zone.dart:1314)
_BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:336)
_BufferingStreamSubscription._add (dart:async/stream_impl.dart:263)
_SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:764)
_StreamController._add (dart:async/stream_controller.dart:640)
_StreamController.add (dart:async/stream_controller.dart:586)
_Socket._onData (dart:io-patch/socket_patch.dart:1829)
_RootZone.runUnaryGuarded (dart:async/zone.dart:1314)
_BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:336)
_BufferingStreamSubscription._add (dart:async/stream_impl.dart:263)
_SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:764)
_StreamController._add (dart:async/stream_controller.dart:640)
_StreamController.add (dart:async/stream_controller.dart:586)
new _RawSocket. (dart:io-patch/socket_patch.dart:1377)
_NativeSocket.issueReadEvent.issue (dart:io-patch/socket_patch.dart:897)
_microtaskLoop (dart:async/schedule_microtask.dart:41)
_startMicrotaskLoop (dart:async/schedule_microtask.dart:50)
_runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:116)
_RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:173)
and the Log from the lib is as follow:
FINE: 2019-11-20 00:23:56.001133: readyState closed
FINE: 2019-11-20 00:23:56.005139: opening http://192.168.8.100:4040
FINE: 2019-11-20 00:23:56.009135: creating transport "websocket"
FINE: 2019-11-20 00:23:56.048133: setting transport websocket
FINE: 2019-11-20 00:23:56.049133: connect attempt will timeout after 20000
FINE: 2019-11-20 00:23:56.054139: readyState opening
FINE: 2019-11-20 00:23:56.055133: emitting packet with ack id 0
#Error thrown here. The rest of the log is printed only when the program is killed
FINE: 2019-11-20 00:23:56.171132: socket receive: type "open", data "{"sid":"5A3hRkmhTPSJheS_AAAT","upgrades":[],"pingInterval":25000,"pingTimeout":5000}"
FINE: 2019-11-20 00:23:56.182133: socket open
FINE: 2019-11-20 00:23:56.182133: open
FINE: 2019-11-20 00:23:56.184133: cleanup
FINE: 2019-11-20 00:23:56.187132: transport is open - connecting
FINE: 2019-11-20 00:23:56.189134: socket receive: type "message", data "0"
FINE: 2019-11-20 00:23:56.201133: writing packet {type: 2, data: [authenticate, {strategy: local, email: [email protected], password: test69}], options: {compress: false}, id: 0, nsp: /}
FINE: 2019-11-20 00:23:56.202133: encoding packet {type: 2, data: [authenticate, {strategy: local, email: [email protected], password: test69}], options: {compress: false}, id: 0, nsp: /}
FINE: 2019-11-20 00:23:56.205132: encoded {type: 2, data: [authenticate, {strategy: local, email: [email protected], password: test69}], options: {compress: false}, id: 0, nsp: /} as 20["authenticate",{"strategy":"local","email":"[email protected]","password":"test69"}]
FINE: 2019-11-20 00:23:56.206132: flushing 1 packets in socket
FINE: 2019-11-20 00:23:57.385134: socket receive: type "message", data "30[null,{"accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6ImFjY2VzcyJ9.eyJpYXQiOjE1NzQyMDU4MzcsImV4cCI6MTU3NDI5MjIzNywiYXVkIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImlzcyI6ImZlYXRoZXJzIiwic3ViIjoiMSIsImp0aSI6IjMxYTI4NmE4LTlhZWYtNDhkZS1iZmQ2LWJlZjk3MDFlYWE0ZSJ9.8OAhWPG-IiHRGOZJmXU3XBWnAeySa4qhvE47GGtbmuA","authentication":{"strategy":"local"},"user":{"id":"1","email":"[email protected]","googleId":null,"facebookId":null,"deviceUuid":null,"male_gender":null,"birthdate":null,"city":null,"country":null,"position":null,"langs":null,"disabled":null,"parent":null,"last_connection":null,"createdAt":"2018-08-03T19:05:48.043Z","updatedAt":"2018-08-03T19:05:48.043Z"}}]"
FINE: 2019-11-20 00:23:57.389134: calling ack 0 with [null, {accessToken: eyJhbGciOiJIUzI1NiIsInR5cCI6ImFjY2VzcyJ9.eyJpYXQiOjE1NzQyMDU4MzcsImV4cCI6MTU3NDI5MjIzNywiYXVkIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImlzcyI6ImZlYXRoZXJzIiwic3ViIjoiMSIsImp0aSI6IjMxYTI4NmE4LTlhZWYtNDhkZS1iZmQ2LWJlZjk3MDFlYWE0ZSJ9.8OAhWPG-IiHRGOZJmXU3XBWnAeySa4qhvE47GGtbmuA, authentication: {strategy: local}, user: {id: 1, email: [email protected], googleId: null, facebookId: null, deviceUuid: null, male_gender: null, birthdate: null, city: null, country: null, position: null, langs: null, disabled: null, parent: null, last_connection: null, createdAt: 2018-08-03T19:05:48.043Z, updatedAt: 2018-08-03T19:05:48.043Z}}]
Exited (sigint)
Strange thing is that even if I call a simple emit function instead of emitWithAck, like this:
_socket.emit("authenticate", {"strategy":"local", "email":"[email protected]", "password":"test69"});
no error is thrown by the app but the log still hang on after the "readyState opening" message and the rest of the log is only printed when the app is killed...
So here is the log I have in this case:
FINE: 2019-11-20 00:23:56.001133: readyState closed
FINE: 2019-11-20 00:23:56.005139: opening http://192.168.8.100:4040
FINE: 2019-11-20 00:23:56.009135: creating transport "websocket"
FINE: 2019-11-20 00:23:56.048133: setting transport websocket
FINE: 2019-11-20 00:23:56.049133: connect attempt will timeout after 20000
FINE: 2019-11-20 00:23:56.054139: readyState opening
**#Log print hang on infinitely here untill the app is killed**
FINE: 2019-11-20 00:23:56.055133: emitting packet with ack id 0
FINE: 2019-11-20 00:23:56.171132: socket receive: type "open", data "{"sid":"5A3hRkmhTPSJheS_AAAT","upgrades":[],"pingInterval":25000,"pingTimeout":5000}"
FINE: 2019-11-20 00:23:56.182133: socket open
FINE: 2019-11-20 00:23:56.182133: open
FINE: 2019-11-20 00:23:56.184133: cleanup
FINE: 2019-11-20 00:23:56.187132: transport is open - connecting
FINE: 2019-11-20 00:23:56.189134: socket receive: type "message", data "0"
FINE: 2019-11-20 00:23:56.201133: writing packet {type: 2, data: [authenticate, {strategy: local, email: [email protected], password: test69}], options: {compress: false}, id: 0, nsp: /}
FINE: 2019-11-20 00:23:56.202133: encoding packet {type: 2, data: [authenticate, {strategy: local, email: [email protected], password: test69}], options: {compress: false}, id: 0, nsp: /}
FINE: 2019-11-20 00:23:56.205132: encoded {type: 2, data: [authenticate, {strategy: local, email: [email protected], password: test69}], options: {compress: false}, id: 0, nsp: /} as 20["authenticate",{"strategy":"local","email":"[email protected]","password":"test69"}]
FINE: 2019-11-20 00:23:56.206132: flushing 1 packets in socket
FINE: 2019-11-20 00:23:57.385134: socket receive: type "message", data "30[null,{"accessToken":"eyJhbGciOiJIUzI1NiIsInR5cCI6ImFjY2VzcyJ9.eyJpYXQiOjE1NzQyMDU4MzcsImV4cCI6MTU3NDI5MjIzNywiYXVkIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImlzcyI6ImZlYXRoZXJzIiwic3ViIjoiMSIsImp0aSI6IjMxYTI4NmE4LTlhZWYtNDhkZS1iZmQ2LWJlZjk3MDFlYWE0ZSJ9.8OAhWPG-IiHRGOZJmXU3XBWnAeySa4qhvE47GGtbmuA","authentication":{"strategy":"local"},"user":{"id":"1","email":"[email protected]","googleId":null,"facebookId":null,"deviceUuid":null,"male_gender":null,"birthdate":null,"city":null,"country":null,"position":null,"langs":null,"disabled":null,"parent":null,"last_connection":null,"createdAt":"2018-08-03T19:05:48.043Z","updatedAt":"2018-08-03T19:05:48.043Z"}}]"
FINE: 2019-11-20 00:23:57.389134: calling ack 0 with [null, {accessToken: eyJhbGciOiJIUzI1NiIsInR5cCI6ImFjY2VzcyJ9.eyJpYXQiOjE1NzQyMDU4MzcsImV4cCI6MTU3NDI5MjIzNywiYXVkIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImlzcyI6ImZlYXRoZXJzIiwic3ViIjoiMSIsImp0aSI6IjMxYTI4NmE4LTlhZWYtNDhkZS1iZmQ2LWJlZjk3MDFlYWE0ZSJ9.8OAhWPG-IiHRGOZJmXU3XBWnAeySa4qhvE47GGtbmuA, authentication: {strategy: local}, user: {id: 1, email: [email protected], googleId: null, facebookId: null, deviceUuid: null, male_gender: null, birthdate: null, city: null, country: null, position: null, langs: null, disabled: null, parent: null, last_connection: null, createdAt: 2018-08-03T19:05:48.043Z, updatedAt: 2018-08-03T19:05:48.043Z}}]
Exited (sigint)
any idea of what might be the issue and how to solve it?
Trying to get work with featherjs and unable to work with the direct connection given at documentation.
Worked well after make this fix.
( L150, lib/src/socket.dart )
// But would break other data type
List sendData = data === null ? [event] : [event, ...data];
Example code:
_socket.emitWithAck('get', [ 'product', 78 ],
ack: (error, data) {
print(error);
});
_socket.emitWIthAck('find', [ 'product' ],
ack: (error, data) {
print(error);
});
And also for arguments when success feathers only return error & data, when error only receive error and dart would throw error.
Error Message:
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: Closure call with mismatched arguments: function 'call'
Hello author! I have a problem now. When I connect to my own nettySocket.io server using a plugin, I keep disconnecting and disconnecting. I ask if this plugin is developed with reference to 2.1.1 or the latest 2.2.0. How should I solve this situation? The server I am ok in other projects, so I spent 2 days looking for bugs. Found that it is not a server problem. I don't know if you can help
I think it's a good idea to have an option to disable the logging or control the level of debugging (Connection status, specific events, etc...)
It becomes cumbersome, when my server sends multiple generic events and the debug message i'm looking for gets lost among them 😅
Hello,
I would enable unit test for my project which use your socket package.
But the following error failed my tests :
The following assertion was thrown running a test:
A Timer is still pending even after the widget tree was disposed.
'package:flutter_test/src/binding.dart':
Failed assertion: line 1056 pos 7: '_currentFakeAsync.nonPeriodicTimerCount == 0'
My test :
I test if a widget can build. This widget contain socket_io and socket_io try to connect. My test do not take care of socket_io so i didn't want wait for connection...
Of can i do that :) ? Or how can i wait for connection ?
Test code :
void main() {
testWidgets('Run app', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(App());
});
}
I'm trying to do authentication via passport using this https://github.com/jfromaniello/passport.socketio but it require authentication cookie to be passed as a header.
I think this is a pretty common usecase and only supporting query params isn't fit for everything.
Would it be possible to add support for headers (just like extraHeaders
in the js client lib https://socket.io/docs/client-api/#With-extraHeaders)
Happy to help if needed :)
Cheers
How to handle socket io callback with this library? In javascript, it looks something like this
socket.emit('authenticate', {
strategy: 'strategyname',
... otherData
}, function(message, data) {
console.log(message); // message will be null
console.log(data); // data will be {"accessToken": "your token"}
// You can now send authenticated messages to the server
});
Hi guys:
in my client as below:
import 'dart:async';
import 'package:socket_io_client/socket_io_client.dart' as IO;
main() {
IO.Socket socket = IO.io('http://127.0.0.1:8090/xy', <String, dynamic>{
'transports': ['polling','websocket'],
'extraHeaders': {'foo': 'bar'}
});
socket.on('connect', () {
print('socket_io_client===>connect http://127.0.0.1:8090/xy');
socket.emit('msg', 'init');
int count = 0;
new Timer.periodic(const Duration(seconds: 20), (Timer countDownTimer) {
socket.emit('msg', count++);
});
});
socket.on('event', (data) => print(data));
socket.on('disconnect', () => print('disconnect http://127.0.0.1:8090/xy'));
socket.on('fromServer', () => print());
}
pubspec.yaml
#socketIO
socket_io_common: ^0.9.0+5
socket_io_client:
git:
url: https://github.com/rikulo/socket.io-client-dart
and my socket server version is "socket.io": "2.0.4"(also try with "2.3.0") on the nodejs server.
now issue: the client cant conn to the server. but if transports replace with 'transports': ['websocket'],it work ok.so how to fix it in my project? thx very much!
I am trying to implement this socket io package in IOS platform, but its throwing error, I have followed the suggestions and implementation part like in the document ( Instructions they gave ), still not working.
Error msg:
CocoaPods' output:
↳
Preparing
Analyzing dependencies
Inspecting targets to integrate
Using `ARCHS` setting to build architectures of target `Pods-Runner`: (``)
Finding Podfile changes
A Socket.IO-Client-Swift
A flutter_socket_io
- Flutter
- fluttertoast
- map_view
- path_provider
- share
- sqflite
- url_launcher
Fetching external sources
-> Fetching podspec for `Flutter` from `.symlinks/flutter/ios`
-> Fetching podspec for `flutter_socket_io` from `.symlinks/plugins/flutter_socket_io/ios`
-> Fetching podspec for `fluttertoast` from `.symlinks/plugins/fluttertoast/ios`
-> Fetching podspec for `map_view` from `.symlinks/plugins/map_view/ios`
-> Fetching podspec for `path_provider` from `.symlinks/plugins/path_provider/ios`
-> Fetching podspec for `share` from `.symlinks/plugins/share/ios`
-> Fetching podspec for `sqflite` from `.symlinks/plugins/sqflite/ios`
-> Fetching podspec for `url_launcher` from `.symlinks/plugins/url_launcher/ios`
Resolving dependencies of `Podfile`
Comparing resolved specification to the sandbox manifest
A FMDB
A Flutter
A GoogleMaps
A Socket.IO-Client-Swift
A Starscream
A flutter_socket_io
A fluttertoast
A map_view
A path_provider
A share
A sqflite
A url_launcher
Downloading dependencies
-> Installing FMDB (2.7.5)
> Copying FMDB from `/Users/harshavardhan/Library/Caches/CocoaPods/Pods/Release/FMDB/2.7.5-2ce00` to `Pods/FMDB`
-> Installing Flutter (1.0.0)
-> Installing GoogleMaps (2.7.0)
> Copying GoogleMaps from `/Users/harshavardhan/Library/Caches/CocoaPods/Pods/Release/GoogleMaps/2.7.0-f79af` to `Pods/GoogleMaps`
-> Installing Socket.IO-Client-Swift (13.3.1)
> Copying Socket.IO-Client-Swift from `/Users/harshavardhan/Library/Caches/CocoaPods/Pods/Release/Socket.IO-Client-Swift/13.3.1-79f8f` to `Pods/Socket.IO-Client-Swift`
-> Installing Starscream (3.0.6)
> Copying Starscream from `/Users/harshavardhan/Library/Caches/CocoaPods/Pods/Release/Starscream/3.0.6-ef3ec` to `Pods/Starscream`
-> Installing flutter_socket_io (0.0.1)
-> Installing fluttertoast (0.0.2)
-> Installing map_view (0.0.12)
-> Installing path_provider (0.0.1)
-> Installing share (0.5.2)
-> Installing sqflite (0.0.1)
-> Installing url_launcher (0.0.1)
- Running pre install hooks
[!] Unable to determine Swift version for the following pods:
- `Socket.IO-Client-Swift` does not specify a Swift version and none of the targets (`Runner`) integrating it have the `SWIFT_VERSION` attribute set. Please contact the author or set the `SWIFT_VERSION` attribute in at least one of the targets that integrate this pod.
/usr/local/Cellar/cocoapods/1.6.1/libexec/gems/cocoapods-1.6.1/lib/cocoapods/installer/xcode/target_validator.rb:115:in `verify_swift_pods_swift_version'
/usr/local/Cellar/cocoapods/1.6.1/libexec/gems/cocoapods-1.6.1/lib/cocoapods/installer/xcode/target_validator.rb:37:in `validate!'
/usr/local/Cellar/cocoapods/1.6.1/libexec/gems/cocoapods-1.6.1/lib/cocoapods/installer.rb:459:in `validate_targets'
/usr/local/Cellar/cocoapods/1.6.1/libexec/gems/cocoapods-1.6.1/lib/cocoapods/installer.rb:138:in `install!'
/usr/local/Cellar/cocoapods/1.6.1/libexec/gems/cocoapods-1.6.1/lib/cocoapods/command/install.rb:48:in `run'
/usr/local/Cellar/cocoapods/1.6.1/libexec/gems/claide-1.0.2/lib/claide/command.rb:334:in `run'
/usr/local/Cellar/cocoapods/1.6.1/libexec/gems/cocoapods-1.6.1/lib/cocoapods/command.rb:52:in `run'
/usr/local/Cellar/cocoapods/1.6.1/libexec/gems/cocoapods-1.6.1/bin/pod:55:in `<top (required)>'
/usr/local/Cellar/cocoapods/1.6.1/libexec/bin/pod:22:in `load'
/usr/local/Cellar/cocoapods/1.6.1/libexec/bin/pod:22:in `<main>'
Error output from CocoaPods:
↳
[!] Automatically assigning platform `ios` with version `8.0` on target `Runner` because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`.
Error running pod install
Error launching application on iPhone Xʀ.
Exited (sigterm)
is there any support for dart sdk 2.0 and is there any road map for flutter support?
I tried just a basic server and client using the example code (fixing the typos), and I can't get it working. It complains about a bool vs null issue in socket_io_client.dart line 53. I fixed that by changing it to check if opts['forceNew'] != null || opts['force new connection'] != null, but then there's another error about "type '() => dynamic' is not a subtype of type 'EventHandler' of 'handler'"
Direction please?!
Question:
Is there a way to check the current status of the socket to determine if it's connected or not?
When connecting to a socket with extraHeaders parameter it is ignored in Flutter Web. The parameter is used fine in iOS and Andriod. Specificlly, the parameter I used i "Authorization" to pass the token at the time of establishing the connection.
In release version (flutter), no ping packets are sent, so connection is dropped by server
Hi,
I'm trying to change the timeout to 1000 from the default setting of 20000. Here's my code:
socket = IO.io('https://www.honeybeehub.ca/chat', <String, dynamic>{
'timeout': 1000,
'reconnectDelay': 3000,
'query': {
'token': accessToken,
},
'transports': ['websocket'],
'upgrade': false,
'reconnection': true
});
socket.on('connect_error', (data) {
print('reconnecting');
});
Everything else with my socket is working perfect. It's just that the timeout is not. Thanks
import 'package:socket_io/socket_io.dart';
import 'package:socket_io_client/socket_io_client.dart' as IO;
main() {
IO.Socket socket = IO.io('http://localhost:8000');
socket.on('connect', (_) {
print('connect');
socket.emit('msg', 'test');
});
socket.on('event', (data) => print(data));
socket.on('disconnect', (_) => print('disconnect'));
socket.on('fromServer', (_) => print(_));
}
//node js server
const io = require("socket.io"),
server = io.listen(8000);
let sequenceNumberByClient = new Map();
server.on("connection", socket => {
console.info(Client connected [id=${socket.id}]
);
sequenceNumberByClient.set(socket, 1);
socket.on("disconnect", () => {
sequenceNumberByClient.delete(socket);
console.info(Client gone [id=${socket.id}]
);
});
});
Can you use socket. IO Node version at the same time?
能不能与 socket.io Node版本 同时使用?
Is there any plan for a Flutter version of this?
Refer to this discussion - #37
still not working?
Hi. I am new in Dart ecosystem and trying to write simple client to connect socket.io server. Running next code running errors. Can anybody help me fix this. Thanks
Code
import 'package:socket_io_client/socket_io_client.dart' as IO;
main(List<String> args) {
print('start app');
IO.Socket socket = IO.io('http://localhost:3000');
socket.on('connect', (_) {
print('connect');
socket.emit('msg', 'test');
socket.emit('chat message', 'test_msg');
});
socket.on('chat message', (data) {
print('dsadasdas');
print(data);
});
socket.on('event', (data) => print(data));
socket.on('disconnect', (_) => print('disconnect'));
socket.on('fromServer', (_) => print(_));
}
Errors
file:///home/faker/.pub-cache/hosted/pub.dartlang.org/socket_io_client-0.9.0+1/lib/src/engine/socket.dart:15:8: Error: Not found: 'dart:html'
import 'dart:html';
^
file:///home/faker/.pub-cache/hosted/pub.dartlang.org/socket_io_client-0.9.0+1/lib/src/engine/transport/jsonp_transport.dart:2:8: Error: Not found: 'dart:html'
import 'dart:html';
^
file:///home/faker/.pub-cache/hosted/pub.dartlang.org/socket_io_client-0.9.0+1/lib/src/engine/transport/websocket_transport.dart:14:8: Error: Not found: 'dart:html'
import 'dart:html';
^
file:///home/faker/.pub-cache/hosted/pub.dartlang.org/socket_io_client-0.9.0+1/lib/src/engine/transport/xhr_transport.dart:2:8: Error: Not found: 'dart:html'
import 'dart:html';
^
file:///home/faker/.pub-cache/hosted/pub.dartlang.org/socket_io_client-0.9.0+1/lib/src/engine/transport/jsonp_transport.dart:3:8: Error: Not found: 'dart:js'
import 'dart:js';
^
file:///home/faker/.pub-cache/hosted/pub.dartlang.org/socket_io_client-0.9.0+1/lib/src/engine/transport/jsonp_transport.dart:35:3: Error: Type 'ScriptElement' not found.
ScriptElement script;
^^^^^^^^^^^^^
file:///home/faker/.pub-cache/hosted/pub.dartlang.org/socket_io_client-0.9.0+1/lib/src/engine/transport/jsonp_transport.dart:36:3: Error: Type 'FormElement' not found.
FormElement form;
^^^^^^^^^^^
file:///home/faker/.pub-cache/hosted/pub.dartlang.org/socket_io_client-0.9.0+1/lib/src/engine/transport/jsonp_transport.dart:37:3: Error: Type 'IFrameElement' not found.
IFrameElement iframe;
^^^^^^^^^^^^^
file:///home/faker/.pub-cache/hosted/pub.dartlang.org/socket_io_client-0.9.0+1/lib/src/engine/transport/jsonp_transport.dart:38:3: Error: Type 'TextAreaElement' not found.
TextAreaElement area;
^^^^^^^^^^^^^^^
file:///home/faker/.pub-cache/hosted/pub.dartlang.org/socket_io_client-0.9.0+1/lib/src/engine/transport/websocket_transport.dart:29:3: Error: Type 'WebSocket' not found.
WebSocket ws;
^^^^^^^^^
Dart version
☁ socket_io dart --version
Dart VM version: 2.1.0 (Unknown timestamp) on "linux_x64"
When using Socket.io with Flutter Web and sending ArrayBuffers over the pipe, the browser throws the following exception:
Uncaught Error: NoSuchMethodError: '[]'
Dynamic call of null.
Receiver: Instance of 'NativeByteBuffer'
Arguments: [0]
at Object.throw_ [as throw] (errors.dart:196)
at Object.defaultNoSuchMethod (operations.dart:667)
at ArrayBuffer.noSuchMethod (core_patch.dart:63)
at Object.noSuchMethod (operations.dart:662)
at callNSM (operations.dart:255)
at Object._checkAndCall (operations.dart:268)
at Object.callMethod (operations.dart:390)
at Object.dsend (operations.dart:394)
at Function.decodePacket (parser.dart:170)
at websocket_transport.WebSocketTransport.new.onData (transport.dart:121)
at websocket_transport.dart:59
at Object._checkAndCall (operations.dart:326)
at Object.dcall (operations.dart:331)
at WebSocket.<anonymous> (html_dart2js.dart:35657)
I saw, that the required code portion is in place, but unfortunately commented out.
if (data instanceof ArrayBuffer) {
data = arrayBufferToBuffer(data);
}
https://github.com/rikulo/socket_io_common/blob/master/lib/src/engine/parser/parser.dart#L167
I tried adapting the implementation to automatically detect the ArrayBuffer
, and it seems to (at least) stop throwing exceptions:
if (binaryType == 'arraybuffer' || runtimeType == 'ByteBuffer') { // || data.runtimeType == 'NativeByteBuffer'
// wrap Buffer/ArrayBuffer data into an Uint8Array
var intArray = (data as ByteBuffer).asUint8List();
type = intArray[0];
return {'type': PacketTypeList[type], 'data': intArray.sublist(0)};
}
Would this be a suitable approach?
So I have my listeners on initState
...
socket.on('synchronizedata', (packet) {
print('packet of type ${packet['packetKind']}!-> $packet');
_syncMessages(context, _message);
});
but when the server emits synchronizedata
, the code above is fired twice. Any thoughts? Initially, I have them on the build
method, but after reading [issue #15], I placed them into initState
.
Any thoughts?
I'm so confused how to use this in flutter.
I have a state class and use this in initState:
_socket = IO.io(SERVER, <String, dynamic>{ 'transports': ['websocket'], }); _socket.emit(EMIT, _emitData); _socket.on(MESSAGE_RSV, (message) { if (mounted) { setState(() { print(message['message']); }); } });
then if I close this state and then reopen it:
_socket.on(MESSAGE_RSV, (message) { if (mounted) { setState(() { print(message['message']); }); } });
doesn't work!
Is destroy needed in dispose state?
I used connect function but soket.on
called twice.
Is there a strong Flutter example?
i follow instruction code as below:
IO.Socket socket = IO.io("http://host.com:port",);
i debug break point realized it's Manager never drop into open ->
// emit open
var openSub = ON.on(socket, 'open', (_) {
onopen(); <-------never come this line for open connection
if (callback != null) callback();
});
But i work on native code, please help me, thanks
I tried to use the library to connect to the socket.io server, but I ran into this error【SERVER_URL】. This is my client implementation, can someone help me?
static const String CHAT_SERVER_URL = "https://socket-io-chat.now.sh/";
this server connect [OK]
static const String SERVER_URL = "http://192.168.1.10:8911/";
this server connect [ERROR ] ->tips: [was not upgraded to websocket ], Very embarrassing is that I can use the java library to connect successfully.
class ArchivesSocket {
IO.Socket socket;
void initSocketIOClient() {
print('init socket.io');
// socket = IO.io(Data.RECEIVE_SOCKET_CHANNEL, <String, dynamic>{
socket = IO.io(Data.SERVER_URL, <String, dynamic>{
'transports': ['websocket'],
"header":[]
});
socket.on('connect', (_) {
print('connect success...');
emit(Data.event_begin_scan, "test");
});
socket.on('connect_error', (data) {
print("socket connect exception :$data");
});
socket.on('connect_timeout', (data) {
print(data);
});
socket.on(Data.event_begin_scan, (data) {
print(data);
});
socket.on(Data.event_scanning, (data) {
print(data);
});
socket.on(Data.event_warehousing_confirm_complete, (data) {
print(data);
});
socket.on(Data.event_outbound_confirm_complete, (data) {
print(data);
});
}
}
I don't see this package listed in pub. Should we just point directly to the git repo to use it?
How to do like this
socket.join('some room');
?
According to this issue dart-lang/sdk#31149
we should change the implementation of this line -
this.emit(event, data);
to avoid dart2js issue.I've setup a SocketIO client in my Flutter project, and can successfully connect to a local SocketIO server. The connect and disconnect events work, and I am able to emit data to the server, however when the server emits data the client's events don't fire.
Code for client:
IO.Socket socket = IO.io('http://127.0.0.1:5000', <String, dynamic>{
'transports': ['websocket']
});
socket.on('connect', (_) {
print('connected');
socket.emit('message', {'message': 'hello'});
});
socket.on('message', (data) {
print(data);
});
socket.on('disconnect', (_) => print('disconnect'));
The server is written in Python using Flask-SocketIO, and I know the implementation is correct as it can communicate fine with Python and C# SocketIO programs.
Flutter version: 1.9.1+hotfix.4
socket_io_client version: ^0.9.4
I suspected this might have been a firewall problem however I was able to run a similar Python SocketIO server and send and receive messages on the same computer.
Any help is appreciated.
as title.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.