Flutter and websocket client issue

9,238 views
Skip to first unread message

Chi Thanh Nguyen

unread,
Dec 5, 2017, 3:16:03 PM12/5/17
to Flutter Dev
Hi all,

I am new to dart and flutter. 
I have a plan to make some prototype of phone app and have found flutter is amazing. 
Though I have a blocking point which is the websocket functionality in the frontend. 

My project is a mobile app implemented with flutter, and the server app implemented in C++. They interact through websocket.

I have my app written in flutter, very simple 
import 'dart:io';
main() async {
//var socket = await WebSocket.connect('ws://10.0.2.2:9090');
//var socket = await WebSocket.connect('ws://localhost:8080');
var socket = await WebSocket.connect('ws://localhost:9123/ws'); /// example on official dart page
socket.add('Hello, World!');
}

And my websocker server that I write in C++ and run it in debug mode, so I can check if any client connects to it. I tested with my own C++ client app and it can prove my server work. But when I run the flutter code above, flutter cannot perform the websocket connection. 

Performing full restart...
Restarted app in 677ms.
E/flutter ( 3235): [ERROR:lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter ( 3235): SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 38925
E/flutter ( 3235): #0      main (/data/user/0/com.yourcompany.currencyswap/cache/currency_swapdPDVmh/currency_swap/lib/main.dart:8:16)
E/flutter ( 3235): <asynchronous suspension>
E/flutter ( 3235): #1      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:265)
E/flutter ( 3235): #2      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:151)
Lost connection to device. 

I've noticed that the port that the app runs is 38925 despite I specified 9123 in my source code. 
Can anybody help please. 

Thank you very much
Chi

Below is my flutter doctor
[√] Flutter (on Microsoft Windows [Version 10.0.15063], locale en-CA, channel alpha)
    • Flutter at C:\DevLib\flutter
    • Framework revision d957c8f040 (5 days ago), 2017-11-30 13:29:59 -0800
    • Engine revision 77d8acb9be
    • Tools Dart version 1.25.0-dev.11.0
    • Engine Dart version 2.0.0-dev.9.0

[√] Android toolchain - develop for Android devices (Android SDK 26.0.1)
    • Android SDK at C:\Users\ctnguyen\AppData\Local\Android\sdk
    • Unable to locate Android NDK.
      
    • Unable to locate compiler in Android NDK.
      
    • Platform android-26, build-tools 26.0.1
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_112-release-b06)

[√] Android Studio (version 2.3)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Java version OpenJDK Runtime Environment (build 1.8.0_112-release-b06)

[√] IntelliJ IDEA Community Edition (version 2017.2)
    • Flutter plugin version 17.0
    • Dart plugin version 172.3968.27

[√] Connected devices
    • Android SDK built for x86 • emulator-5554 • android-x86 • Android 7.0 (API 24) (emulator)

Ian Hickson

unread,
Dec 5, 2017, 4:36:08 PM12/5/17
to Chi Thanh Nguyen, Flutter Dev
I believe the port number you are seeing here is the _local_ port, the source port, not the destination port.
I recommend filing a bug at https://github.com/dart-lang/sdk/issues/new


--
You received this message because you are subscribed to the Google Groups "Flutter Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--

--
Ian Hickson

😸

Chi Thanh Nguyen

unread,
Dec 6, 2017, 3:00:40 AM12/6/17
to Ian Hickson, Flutter Dev
Hi Ian,

I finally found the solution for my issue. It is the way Android emulator connect to the local host that use the ip 10.0.2.2 instead of the usual localhost ip adress. 


So finally the code below works 

  var socket = await WebSocket.connect('ws://10.0.2.2:9090'); // For Android Simulator, run on 10.0.2.2 (windows)
  socket.add('Hello, World!');

Thanks a lot for your help



Kind regards, 

Chi Thanh NGUYEN
+44 77 43 86 96 42
chithanhn...@gmail.com
http://nguyenchithanh.free.fr



To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev+unsubscribe@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.
--

--
Ian Hickson

😸

Eric Seidel

unread,
Dec 6, 2017, 11:48:34 AM12/6/17
to Chi Thanh Nguyen, Flutter Dev
That makes sense.  The Android emulator has separate network devices from the host (desktop) machine, so "localhost" in code run inside the emulator would try to connect to the emulator itself.

You can also use adb to set up port forwarding from the emulator to your desktop so that certain ports in the emulator's view of "localhost" would map to other ports on the desktop.  Make sense?

On Tue, Dec 5, 2017 at 12:16 PM Chi Thanh Nguyen <chithanhn...@gmail.com> wrote:
--
You received this message because you are subscribed to the Google Groups "Flutter Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev...@googlegroups.com.

Niyazi Toros

unread,
Jun 27, 2018, 1:29:47 AM6/27/18
to Flutter Dev
Hi Chi,

How to get response after socket.add('Hello, World!');?
I am testing my socket using telnet and its working. I can connect my flutter app and I can get connected and send the data like "hello world" and it supposed to get me back saying "Hi There"

But I can get any data from stream;
new StreamBuilder(
stream: widget.channel.stream,
builder: (context, snapshot) {
return new Padding(
padding: const EdgeInsets.all(20.0),
child: new Text(snapshot.hasData ? '${snapshot.data}' : ''),
);
},
)

Any help please?

Chi Thanh Nguyen

unread,
Jun 27, 2018, 3:55:57 AM6/27/18
to Niyazi Toros, Flutter Dev
Hi Nazi,

I didn't use the StreamBuilder, instead I use directly the stream after connecting the socket, then bind the stream to 2 callbacks. Something like this : 


===============================================
WebSocket.connect(_myURL).then((myConnectedSocket) {
   print('My socket is connected');
   myConnectedSocket.map(myCallback1).listen(myCallback2);
   // You can send 'hello world!' from here.
});

MessageType myCallback1(List<int> rawbuffer){
   print('Receiving data stream from the server : ' + rawbuffer.toString());
    // Do some deserialization and decryption from the received rawbuffer here, return the deserialized data in form of MessageType
    // If you don't have serialization and encryption step, just try to convert the buffer to a string, so MessageType would be String
}


void myCallback2(MessageType receivedMsg){
    print('Message Handler is called');
    // Handle the receivedMsg, do what you want when receive it, e.g print its data?
}
===============================================
Once you can get the stream work with my way, that ensure the connection/send/receive data is correct, then you can find a way to make it work with StreamBuilder as yours.

Hope that can help

Chi



--
You received this message because you are subscribed to a topic in the Google Groups "Flutter Dev" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/flutter-dev/jAQTX6Dyyyo/unsubscribe.
To unsubscribe from this group and all its topics, send an email to flutter-dev+unsubscribe@googlegroups.com.

Maik Mewes

unread,
Jun 27, 2018, 4:08:56 AM6/27/18
to Chi Thanh Nguyen, Niyazi Toros, Flutter Dev
When working with websockets keep in mind that there might be issues when it comes to real devices with newer android versions, at least with secure web sockets.


Maik

To unsubscribe from this group and all its topics, send an email to flutter-dev...@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Flutter Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev...@googlegroups.com.

Niyazi Toros

unread,
Jun 27, 2018, 5:43:29 AM6/27/18
to Flutter Dev
Thanks Chi, I will try that

Niyazi Toros

unread,
Jun 28, 2018, 2:34:30 AM6/28/18
to Flutter Dev

Hi Chin,


I am new to flutter or dart socket programming. Is it possible to share the code? It seems that not streamBuilder but the stream is my solution but couldn't accomplish.

In you code I found that there is a missing part for me such as how to or where define the myConnectedSocket? 

Also you comment that I can send the command here part means can I add like socket.add('Hello, World!');?


I try to access my socket via telnet and its working. As shown below. If I use flutter_websocket example I can see I can connect to server and when I send data nothing happens.


Here is my telnet example: I like to implement this and get the value and show in flutter text.



Niyazis-MBP:~ niyazitoros$ telnet

telnet> telnet 192.168.1.22 1024

Trying 192.168.1.22...

Connected to 192.168.1.22.

Escape character is '^]'.

Q101:_:49785:_:*************

1:_:2:_:119351:_:NİYAZİ TOROS





===============================================
WebSocket.connect(_myURL).then((myConnectedSocket) {
   print('My socket is connected');
   myConnectedSocket.map(myCallback1).listen(myCallback2);
   // You can send 'hello world!' from here.
});

MessageType myCallback1(List<int> rawbuffer){
   print('Receiving data stream from the server : ' + rawbuffer.toString());
    // Do some deserialization and decryption from the received rawbuffer here, return the deserialized data in form of MessageType
    // If you don't have serialization and encryption step, just try to convert the buffer to a string, so MessageType would be String
}


void myCallback2(MessageType receivedMsg){
    print('Message Handler is called');
    // Handle the receivedMsg, do what you want when receive it, e.g print its data?
}
=============================================== 

Reply all
Reply to author
Forward
0 new messages