September 13, 2021

Socket connection in flutter app – Client side

By lj

Socket connection

Socket is made of server and client. Server will host party or it is like walk-in interview, where anyone can come and show their talent. In our terms, it can be a computer which is bounded to particular address (host name) and specific port number. On the other hand client is guest or another member of party who talks with organizer, In our terms it can be a browser or application, which already knows address and port where server is listening. 

Why Socket connection

Socket is basically used when we want to work with shared resources. You can compare it with whatsapp group, Group is like a server which is with particular name and port, and all group members are client. When admin sends message, all group member can see at a time. This is just similar to it, but not exactly. You might be familiar with whatsapp web, you are scanning qr code from whatsapp app and you can access all your chats in website.

It is easy right? We can use socket connection at this scenario. You can notice when you send message from your app, web reflects same, it is also same for vice versa. We can manage this situation with Socket connection. Another useful example is apps like xender and shareit, who also works on basis of socket. One device creates Server and all other joins it, and share files.

Socket Client

This post is particular about client side in flutter. So let’s move to flutter code. To create socket client we will user Socket from dart:io. Let’s create variable which holds our socket.

Socket? _channel

Now, initialize socket as below when actually needed : 

_channel = await Socket.connect('***.***', PORT_NUMBER);

It is connected with server, if you didn’t get error on console. So, only connection with server is not complete step. We need to listen and also send some information from client. Let’s write code to listen messages from server:

_channel?.listen((event) {
  debugPrint("new message from socket - ${utf8.decode(event).trim()}");
}, onDone: () {
  _channel = null;
  debugPrint("socket connection done");
  // createAndListenChannel();
}, onError: (error) {
  _channel = null;
  debugPrint("Socket connection error - $error");
}, cancelOnError: false);

Above code is for listening from server, onError is for detecting error in stream (not handle socket exception), onDone – used when stream is done transferring data. Now we need to know how to send data in server, for that we just use add method in socket :

_channel?.add(utf8.encode("Hello messages --"));

This is all about coding site of client.

Conclusion

To use socket in app, dart’s dart:io package have tool. Use Socket to create client side of code, If you are building xender like app, so you might also need to use ServerSocket for server code. Just clear concept of socket and code you can find here.

Thanks for reading, Open for your comments and suggestions.