Sockets in Dart
Implement real-time network communication for your applications
Download Complete ExamplesWhat are Sockets?
Sockets are communication endpoints that let different processes exchange data, whether on the same machine or over a network. In Dart, socket-based communication is fundamental for client-server applications, real-time chat, multiplayer games and more.
Bidirectional Communication
Client and server can send and receive data simultaneously
Real Time
Instant communication without needing to refresh
Client/Server Architecture
Multiple clients can connect to the same server
Socket Architecture
Client
Server
Necessary Imports:
import 'dart:io'; // Para sockets TCPimport 'dart:convert'; // Para codificación/decodificación
Creating a Socket Server
1. Import dependencies
We import the necessary libraries to handle sockets and input/output.
2. Bind the server
We specify the IP address and port where the server will listen for connections.
3. Handle connections
We listen for incoming connections and handle the received data.
4. Handle multiple clients
We keep a list of connected clients for broadcasting.
Complete Server:
import 'dart:io';
void main() async {
// Paso 2: Vincular servidor al puerto 3456 final server = await ServerSocket.bind(
InternetAddress.loopbackIPv4, // 127.0.0.1
3456
);
List clientes = [];
print('Servidor iniciado en ${server.address.address}:${server.port}');
// Paso 3: Escuchar conexiones entrantes server.listen((Socket cliente) {
print("Cliente conectado desde ${cliente.remoteAddress.address}");
// Enviar mensaje de bienvenida cliente.write("¡Bienvenido a este servidor! \n");
// Paso 4: Añadir cliente a la lista clientes.add(cliente);
// Escuchar mensajes del cliente cliente.listen(
(List data) {
String mensaje = String.fromCharCodes(data).trim();
print('Mensaje recibido: ${mensaje}');
// Responder al cliente cliente.write("Mensaje recibido \n");
// Broadcast a otros clientes for (var user in clientes) {
if (user != cliente) {
user.write("Cliente dice: \$mensaje \n");
}
}
// Comando especial 'info' if (mensaje == "info") {
cliente.write("Clientes conectados: \${clientes.length} \n");
}
},
onDone: () {
print('Cliente desconectado');
clientes.remove(cliente);
},
onError: (error) {
print("Error: ${error}");
clientes.remove(cliente);
},
);
});
}
Creating a Socket Client
1. Connect to the server
We establish a connection to the server using an IP address and port.
2. Configure listeners
We set up handlers to receive data from the server.
3. Read user input
We capture console input to send to the server.
4. Handle disconnection
We implement logic to close the connection cleanly.
Complete Client:
import 'dart:io';
import 'dart:convert';
void main() async {
// Paso 1: Conectar al servidor final socket = await Socket.connect('127.0.0.1', 3456);
print("Conectado al servidor");
socket.write("Cliente conectado");
// Paso 2: Escuchar respuestas del servidor socket.listen(
(List data) {
String mensaje = String.fromCharCodes(data).trim();
print("Server: \${mensaje}");
},
onDone: () {
print('Conexión perdida con el servidor');
exit(0);
},
onError: (error) {
print("Error: ${error}");
},
);
// Paso 3: Leer entrada del usuario stdin.transform(utf8.decoder).listen((String texto) {
texto = texto.trim();
// Paso 4: Manejar comando 'exit' if (texto == 'exit') {
print('Desconectando...');
socket.write('Cliente cerró la conexión');
socket.close();
exit(0);
} else if (texto.isNotEmpty) {
// Enviar mensaje al servidor socket.write(texto);
}
});
}
Socket Chat Simulator
Connected Clients
Key Properties and Methods
ServerSocket.bind()
Creates and binds a server socket to an address and port
Socket.connect()
Connects a client to a server socket
.listen()
Listens for incoming data on the socket
.write()
Sends data through the socket
.close()
Closes the socket's connection
.remoteAddress
Address of the connected client
Common Use Cases
💬 Real-Time Chat
Instant messaging applications with multiple connected users.
🎮 Multiplayer Games
Real-time state synchronization between players.
📊 Real-Time Monitoring
Dashboard systems that show instantly updated data.
🤖 Communication between Microservices
Data exchange between different components of a distributed system.
Best Practices
🔒 Error Handling
Always implement onError and onDone to handle unexpected disconnections.
💾 Resource Cleanup
Remove disconnected clients from the list to avoid memory leaks.
📨 Data Encoding
Use utf8.decoder/encoder to correctly handle special characters.
⚡ Async/Await
Use asynchronous programming to avoid blocking the main thread.
Exercises to Practice
Exercise 1: Basic Chat
Modify the server so it sends the sender's client name along with each message to all others.
Hint: Store names alongside the sockets and add the name to the broadcast message
Exercise 2: Special Commands
Add commands like "/users" to list users and "/pm [user]" for private messages.
Hint: Check if the message starts with "/" and process it as a command
Exercise 3: Server with Authentication
Implement a system where clients must authenticate with a username/password before chatting.
Hint: When connecting, request credentials before adding to the general list