Dart
Dart
Socket Receive String Until Specific Byte Value is Received
Demonstrates the Chilkat Socket ReceiveStringUntilByte method.Chilkat Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
final sock = CkSocket();
// --------------------------------------------------------------------
// This example uses the public TCP echo service at https://tcpbin.com/
// --------------------------------------------------------------------
final useTls = false;
final port = 4242;
var maxWaitMs = 5000;
try {
sock.connect('tcpbin.com', port, useTls, maxWaitMs);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// Wait a max of 2 seconds for a response..
sock.maxReadIdleMs = 2000;
// Send some strings, each terminated by a 0 byte.
sock.sendString('This is the 1st string');
sock.sendByte(0);
sock.sendString('This is string number 2');
sock.sendByte(0);
// The tcpbin.com echo server only echoes after receiving an LF (linefeed char)
sock.sendByte(10);
// Now let's receive what is echoed back....
// Receive each string and the NULL byte.
// The call to ReceiveStringUntilByte will receive incoming data until the lookForByte is encountered.
// The lookForByte is receive and discarded (it is not returned in the string)
final lookForByte = 0;
final String s1;
try {
s1 = sock.receiveStringUntilByte(lookForByte);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
print(s1);
final String s2;
try {
s2 = sock.receiveStringUntilByte(lookForByte);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
print(s2);
// The echo server will also echo back the final LF
sock.receiveByte(true);
maxWaitMs = 100;
sock.close(100);
// Output:
// This is the 1st string
// This is string number 2
}