Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to use https connection #30

Closed
right7ctrl opened this issue Jul 30, 2019 · 16 comments
Closed

how to use https connection #30

right7ctrl opened this issue Jul 30, 2019 · 16 comments
Labels

Comments

@right7ctrl
Copy link

right7ctrl commented Jul 30, 2019

how to create a secure connection with https

EDIT: solved now, check my answers below

@marianoarga
Copy link

Use HTTPS in the URL.
Otherwise, provide more info of the issue.

@right7ctrl
Copy link
Author

unable to connect, there is no any console message, i tried without ssl it works but this is not.

IO.Socket socket = IO.io("https://io.*******.net/", <String, dynamic>{
      'transports': ['websocket', 'polling'],
      'extraHeaders': {'Access-Control-Allow-Origin': '*'},
    });

I also tried this one too

IO.Socket socket = IO.io("https://io.******.net/", <String, dynamic>{
      'transports': ['websocket', 'polling'],
      'extraHeaders': {'Access-Control-Allow-Origin': '*'},
      'secure': true,
      'rejectUnauthorized': false
    });

@marianoarga
Copy link

marianoarga commented Jul 31, 2019 via email

@right7ctrl
Copy link
Author

our server is already ssl ready, we use in angular to connect socket it works with ssl but unable to connect with this library

@marianoarga
Copy link

@godlessturtle you need a socket.io server, which angular library are you using?

@assemmarwan
Copy link

On a related topic, I am trying to use the options param, but there's no reference for it. For my server I need to include the transport as polling & to add Authorization headers.

I tried the same code Map by @godlessturtle, but I get timeout, 20000.

    _socket = io('$url$path', <String, dynamic>{
      'transports': <String>['polling'],
      'extraHeaders': <String, dynamic>{
        'Authorization': Options.headers['Authorization']
      }
    });

P.S: I am actually porting a JS library to Dart.

@jumperchen
Copy link
Member

Here is my test code to access our https://keikai.io demo and it works well with IO client.
For example,

import 'package:socket_io_client/socket_io_client.dart' as IO;

main() {
  final socket = IO.io('https://keikai.io/foo/...', {
    'transports': ['websocket'], 'query': 'ifAny...'}) as IO.Socket;
  socket.on('connect', (_) {
    print('connect...');
  });
  socket.on('foo', (data) => print('received data...'));
  socket.on('disconnect', (_) => print('disconnect'));
}

The console printed as follows:

/Users/jumperchen/prj/socket_io_client/test/io_client.dart
Observatory listening on http://127.0.0.1:53020/

connect...
received data...
received data...
received data...

Note: if you are using browser client, you don't need to specify the 'transports': ['websocket'], it will use polling first and switch to websocket as socket.io js did.

@assemmarwan
Copy link

What if I have Authorization Headers?

@jumperchen
Copy link
Member

@assemmarwan
Copy link

I would love to contribute 😀
@godlessturtle what is the other library you found.

@right7ctrl
Copy link
Author

adhara socket io
@assemmarwan

@assemmarwan
Copy link

Finally it worked, although it doesn't make sense in my opinion. Here's what I had to do:

    _socket = io(url, <dynamic, dynamic>{
      'path': path,
      'transportOptions': <String, dynamic>{
        'polling': <String, String>{
          'extraHeaders': 'Token <token>'
        }
      }
    });

The equivalent in JS:

    this.socket = IO.connect(args.url, {
      secure: args.url.split("/")[0] === "https:",
      path: args.path,
      transportOptions: {
        polling: {
          extraHeaders: headers
        }
      }
    });

I believe there's a bug with handling the extraHeaders, because I am passing the value without the key 🤷‍♂️

@comispan
Copy link

comispan commented Oct 1, 2019

Hi all, I created a socket.io server in nodejs which allows for HTTPS connection with a self signed certificate. I am trying to get the socket.io client in dart to successfully connect to the server using HTTPS. I have tested the socket.io client in nodejs for HTTPS and it successfully connected.

My client code for dart is

   `import 'package:socket_io_client/socket_io_client.dart' as IO;

main() {

  IO.Socket socket = IO.io('https://localhost', <String, dynamic>{
	'transports': ['websocket'],
	'rejectUnauthorized': false
  });

  socket.on('connect', (_) {
	print('connect');
	socket.emit('message', 'test from dart client 123');
  });

  socket.on('ackmessage', (data) {
	print('Received from server: ' + data);
  });

}`

But at the server side I cannot see any client connected.

@right7ctrl
Copy link
Author

right7ctrl commented Oct 1, 2019

i created a class, and solved my problem approx. 2 months ago
may my code can help you, check this out @comispan

PublishSubject socket = PublishSubject(sync: true);
PublishSubject status = PublishSubject(sync: true);
PublishSubject notify = PublishSubject(sync: true);
PublishSubject chatCount = PublishSubject(sync: true);
PublishSubject typing = PublishSubject(sync: true);
PublishSubject login = PublishSubject(sync: false);
PublishSubject getInfo = PublishSubject(sync: true);
PublishSubject alreadyLogin = PublishSubject(sync: false);

IO.Socket kSocket;

class Sockets {
  static void connectSocket() async {
    /* kSocket = await IO.io('${Strings.socket}', <String, dynamic>{
      'transports': ['websocket', 'polling'],
    });*/
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String token = prefs.getString('userToken');

    if (token != null && token != '') {
      Map<String, dynamic> parsedToken = Functions.parseJwt(token);

      String imza = token?.split('.')[2];
      kSocket = await IO.io('${Strings.socket}', <String, dynamic>{
        'transports': ['websocket', 'polling'],
        'query': 'token=$imza'
      });

      parsedToken['Tur'] = 2;
      kSocket.close();
      kSocket.disconnect();
      kSocket.open();
      try {
        kSocket.on('connect', (data) {
          print('SOCKET CONNECTED');
          kSocket.emit('adduser', parsedToken);
          kSocket.on('getmessage', (res) {
            print('GETMSG: $res');
            chatCount.sink.add(res);
            socket.sink.add(res);
          });
          kSocket.on('bildirim', (res) {
            print('[BILDIRIM]: $res');
            notify.sink.add(res);
          });
          kSocket.on('durum', (res) {
            status.sink.add(res);
          });

          kSocket.on('disconnect', (data) {
           // print('DISCONNECT: $data');
          });

          kSocket.on('typing', (res) {
            typing.sink.add(res);
          });

          kSocket.on('login', (res) {
            //print('Multi Login');
            login.sink.add(res);
          });

          kSocket.on('getinfo', (res) {
            //print('GETINFO: $res');
            getInfo.sink.add(res);
          });

          kSocket.on('alreadylogin', (res) {
            //print('ALREADY LOGIN: $res');
            alreadyLogin.sink.add(res);
          });
        });
      } catch (e) {
        print(e);
      }
    } else {
      print('SOCKET: token yok');
    }
  }

  static void setInfo(Map<String, dynamic> data) {
    kSocket.emit('setinfo', [data]);
  }

  static void setRead(String userid) {
    kSocket.emit('setreaded', '$userid');
  }

  static void isTyping(String username, int status) {
    kSocket.emit('istyping', [
      {"user": int.parse(username), "durum": status}
    ]);
  }

  static void isActive(String userid) {
    if (kSocket != null) {
      if (kSocket.connected) {
        try {
          //print('${kSocket.connected}');
          kSocket.emit('isactive', '$userid');
        } catch (e) {
          print(e);
        }
      }
    }
  }

  static void disconnectSocket() async {
    try {
      await kSocket.disconnect();
      await kSocket.close();
      await kSocket.destroy();
      print('SOCKET DISCONNECTED');
    } catch (e) {
      //print(e);
    }
  }
}

@jumperchen
Copy link
Member

@assemmarwan #34 has supported, please help me to test if it works, thanks.

@assemmarwan
Copy link

@jumperchen I apologize for not responding earlier, but I didn't get a notification 😅

Just upgraded to 0.9.7+1 and it works :) Much appreciated!

For reference, here's what I changed vs. what I previously had.

v0.9.4

    _socket = io(url, <dynamic, dynamic>{
      'path': path,
      'transportOptions': <String, dynamic>{
        'polling': <String, String>{
          'extraHeaders': {{JWTTOKEN}}
        }
      }
    });

v0.9.7+1

    _socket = io(url, <dynamic, dynamic>{
      'path': path,
      'transports': ['websocket'],
      'extraHeaders': <String, String>{
        'Authorization': {{JWTTOKEN}}
      }
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

5 participants