Today’s video will let you know how to create sockets in Flutter to make bi-directional communication possible.
First we will go with the ‘IOWebSocketChannel‘ class.
Watch Video Tutorial
You can read about IOWebSocketChannel by following this link.
Let’s use the Official Sample first.
Create a new file SocketDemo.dart and add the below code into it.
This will create a socket connection with the WebSocket.org which will echo back the message we sent to it.
So let’s create a socket
WebSocketChannel _channel; _channel = IOWebSocketChannel.connect( 'ws://echo.websocket.org' ); void sendMessage() { _channel.sink.add( 'Your Message' ); } @override void dispose() { super .dispose(); _channel.sink.close(); } // the build method, add this StreamBuilder( stream: _channel.stream, builder: (context, snapshot) { return Padding( padding: EdgeInsets.symmetric(vertical: 24.0 ), child: Text(snapshot.hasData ? '${snapshot.data}' : '' ), ); }, ) |
Now if you call sendMessage, you should get the message back.
If you want to do this with your own server you can use the below code
import 'package:web_socket_channel/io.dart' ; import 'package:web_socket_channel/status.dart' as status; main() async { var channel = await IOWebSocketChannel.connect( "ws://<YOUR_SERVER_IP>:<YOUR_PORT>" ); channel.stream.listen((message) { channel.sink.add( "received!" ); channel.close(status.goingAway); }, onDone: () => print( "Stream closed" )); } |
Create our own Server Socket
I am using XAMPP for my local server. You can download XAMPP from here.
Create Server File
After running your server, save this file in the htdocs folder.
<?php $host = "127.0.0.1" ; $port = "6000" ; set_time_limit(0); // create socket $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die ( 'Could not create socket' ); // bind socket to port $result = socket_bind( $socket , $host , $port ) or die ( 'Could not bind to socket' ); // start listening to connections $result = socket_listen( $socket , 3) or die ( 'Could not set up socket listener' ); while (true){ // accept incoming connections // spawn another socket to handle communication $spawn = socket_accept( $socket ) or die ( 'Could not accept incoming connection' ); // read client input $input = socket_read( $spawn , 1024) or die ( 'Could not read input' ); // clean up input string $input = trim( $input ); echo "Client Message: " . $input ; // reverse the message and send back $output = strrev ( $input ); socket_write( $spawn , $output , strlen ( $output )) or die ( 'Could not write output' ); } // Close sockets socket_close( $spawn ); socket_close( $socket ); ?> |
Flutter Sockets
Make sure, you are using the same port as your server and the IP as well.
Also run the server before executing the below code.
Socket _socket; static const String SERVER_IP = "127.0.0.1" ; static const int SERVER_PORT = 6000 ; Future<bool> sendMessage(String message, Function connectionListener, Function messageListener) async { try { _socket = await Socket.connect(SERVER_IP, SERVER_PORT); connectionListener( true ); _socket.listen((List< int > event) { String message = utf8.decode(event); print( 'Message: $message' ); messageListener(message); }); _socket.add(utf8.encode(message)); _socket.close(); } catch (e) { connectionListener( false ); return false ; } return true ; } void cleanUp() { if ( null != _socket) { _socket.destroy(); } } |
Now we have the basic code, you can call this code from your main file like this.
// Call like this _socketUtil.sendMessage(_textEditingController.text, connectionListener, messageListener); // When the socket receives message, this function gets called...check the above code where we're sending this // function as the parameter of the sendMessage function. void messageListener(String message) { setState(() { _messages.add(message); }); print(_messages); } // When the socket gets connected, this function gets called...check the above code where we're sending this // function as the parameter of the sendMessage function. void connectionListener(bool connected) { setState(() { _status = 'Status : ' + (connected ? 'Connected' : 'Failed to connect' ); }); } |
Source Code
You can get the complete source code by cloning this link
git clone https://vipinvijayan1987@bitbucket.org/vipinvijayan1987/tutorialprojects.git
Make sure to switch to “SocketDemo” branch.
How to chat between 2 devices? I am able to send messages to the socket connection and get back to the same phone. How about chatting with another phone?
I will be uploading a tutorial on that. Please stay tuned on my youtube channel.
Hi James,
Any update on your tutorial? I want to create a simple group chat page.
Where people also can see previous chats. I think you also need socket for this right?