Java
Chilkat2 Java
Socket Receive String Until Specific Byte Value is Received
Demonstrates the Chilkat Socket ReceiveStringUntilByte method.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Socket;
public class ChilkatExample {
public static void main(String[] args) {
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
Socket sock = new Socket();
// --------------------------------------------------------------------
// This example uses the public TCP echo service at https://tcpbin.com/
// --------------------------------------------------------------------
boolean useTls = false;
int port = 4242;
int maxWaitMs = 5000;
try {
sock.connect("tcpbin.com", port, useTls, maxWaitMs);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Wait a max of 2 seconds for a response..
sock.setMaxReadIdleMs(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)
int lookForByte = 0;
String s1;
try {
s1 = sock.receiveStringUntilByte(lookForByte);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println(s1);
String s2;
try {
s2 = sock.receiveStringUntilByte(lookForByte);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println(s2);
// The echo server will also echo back the final LF
sock.receiveByte(true);
maxWaitMs = 100;
sock.closeConnection(100);
// Output:
// This is the 1st string
// This is string number 2
}
}