listen method
Implementation
@override
Future<Stream<CommunicateData<Socket>>> listen(
SocketConnectionPoint bind) async {
final StreamController<CommunicateData<Socket>> controller =
StreamController();
_streams.add(controller);
ServerSocket serverSocket = await _bind(bind.address, bind.port);
_servers.add(serverSocket);
// connection
serverSocket.listen((Socket socket) {
_connection.add(socket);
// receive data
socket.listen((Uint8List data) {
// if have not received data yet.
if (_receiveBuffers[socket] == null) {
int bodyPosition = 0;
int dataSize = 0;
// search first LF sign.
// chars until first LF represent the size of this message.
for (int i = 0; i < data.length; i++) {
if (data[i] == utf8.encode("\n").first) {
bodyPosition = i + 1; // the message after first LF.
dataSize = int.parse(utf8.decode(data.sublist(0, i)));
break;
}
}
data = data.sublist(bodyPosition); // change [data] to only the body.
_receiveBuffers[socket] =
CommunicateDataTcp(connection: socket, dataSize: dataSize);
}
final receiveBuffer = _receiveBuffers[socket];
if (receiveBuffer == null) return;
receiveBuffer.receive(data);
// if received all of messages.
if (receiveBuffer.isReceivedAll()) {
controller.sink.add(receiveBuffer.receiveData!); // stream data.
_receiveBuffers.remove(receiveBuffer.connection); // remove buffer.
}
});
});
return controller.stream;
}