Websocket in flutter socket.io client

What is Socket.IO

Socket.IO in Flutter is a Library using which we can enables or give super power to flutter app by enabling real-time communication between clients and servers. WebSocket Technology is perfect for building Application like realTime chat Application, Online Gaming & More.


How Socket.IO Works

We establish a bidirectional a real-time data transmission between client app (flutter) and backend server which will act a WebSockets Server.

In this article, The Flutter Application will act as the client.

Steps:

  • Establish a connection between Client & the Server.
  • The Flutter App will be listening to any incoming event/message from the server.
  • Emet Evenets to broadcast data to backend.
  • Always Close the connection if no longer needed between client and Server.

In this Flutter Articles, We will learn how to make use of Socket.IO Client into our Flutter Application.

Socket.IO in Flutter

Add Dependencies

Get Started by adding the required dependencies i.e. socket_io_client: package into your flutter project pubspec.yaml file.

dependencies:
  socket_io_client: ^2.0.3+1

Import the Library

Once dependencies is been added successfully, To us it you need to import it where required

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

Initialize SocketIO in Flutter

IO.Socket socket = IO.io('http://localhost:3000',
  OptionBuilder()
      .setTransports(['websocket']) // for Flutter or Dart VM
      .setExtraHeaders({'foo': 'bar'}) // optional
      .build());


socket.connect();

socket.onConnect((_) => print(" Connected to Server "));

socket.onConnectError(() => print('Connection Error: $err'));

socket.onError((err)=> print("Error"));

socket.onDisconnect((_)=> print('Disconnected from Server"));

Brief Descriptions of each Socket.IO state methods

onConnect: When WebSocket get connected a callback is triggered.

onDisconnect: We can make use of onDisconnect method to keep checking if socket get disconnected due to some socket.

onConnectError:

is been used to handle if an error occur while connection to socket, a callback will be triggered

onError:

In case if any error occurs during message exchanging between client and server, This can be used to handle the error.


Listening to WebSocket Events

To listen to any incoming message of a specific event topic we make use of on method. On Method can be used in flutter app to listen to incoming messages like displaying new chat message in app that too realtime.

void listenToSocketEvent(){

socket.on('eventName' (data){
   print(' Message received: $data');
});

}

Here replace ‘eventName’ with the event name sent from the server.

Emitting or Sending Events to Listeners

When we want to send a message or data to server or broadcast an event to all the listener we make use of emit method. Making use of emit we can transmit messages or data from client to server immediately.

void sendData(){

  final messageData = {

   'messageId':'abcd123',
   'text':'Hello, This is First Message', 
   'sender':'userName',
   'isImportant':true,
   'timestamp':DataTime.now().toIso8601String(),
  }

}

Closing WebSockets

Always remember to close the Socket connection if not needed. Mostly this can be done when used exit the app.

void closeAllSocketConnection(){

   socket.disconnect();
   socket.dispose();

}

Conclusion

In this Flutter Article We integrated the basic setup of Socket.IO Client in our Flutter Application. If you face any error or need personal guide/help feel free to contact me through email: rajatrrpalankar@gmail.com or social network @rajatpalankar.