How to use sockets in Dart?
Sockets are another common source and destination of input and output in Dart. Sockets are endpoints of communication channels that allow data exchange between processes running on different machines or on the same machine. The dart:io library provides classes and functions to work with sockets and network protocols. To use sockets in Dart, you need to create a Socket object with the host and port of the remote endpoint as arguments. For example, you can create a Socket object for a web server running on localhost and port 80 like this:
import 'dart:io';
var socket = await Socket.connect('localhost', 80);
To write data to a socket, you can use the write() or add() methods of the Socket object. These methods send the given string or list of bytes to the remote endpoint. For example, you can write a HTTP request to the socket like this:
socket.write('GET / HTTP/1.1\r\n');
socket.write('Host: localhost\r\n');
socket.write('\r\n');
To read data from a socket, you can use the listen() method of the Socket object. This method registers a callback function that is invoked when data is available on the socket. The callback function receives a list of bytes as an argument. For example, you can print the HTTP response from the socket like this:
socket.listen((data) {
print(String.fromCharCodes(data));
});