Often when writing client / server applications, the two endpoints talk to one another with a pre-established protocol. One side sends a message to the other and then waits for a specific kind of response.
This would normally involve setting up a second thread to monitor the socket and a complicated set of wait() and notify() calls. Protocol Sockets does all that for you!
A full example is provided in the protocol_sockets.example package, but here is a brief snipit:
ProtocolSocket socket = new ProtocolSocket("example.com", 12345);
String[] names = socket.sendAndWaitForResponse("What is your full name?",
"My name is (.*) (.*)");
System.out.println("His first name is " + names[0] +
" and his last name is " + names[1]);The sendAndWaitForResponse(String, String) method sends a message over the socket and then blocks until the socket receives input matching the regular expression "My name is (.*) (.*)".
When the other side responds with something like "My name is Stephen Ware", the method returns an array of strings corresponding to each group captured in parenthesis in the regular expression.
The calling thread blocks, but the socket does not. It continues to receive input normally, waiting for input that matches the regex. If other input arrives in the mean time, that gets reported normally via...
Protocol Sockets also take the hassle out of starting a new thread to listen for input on the socket. Similar to GUI events in Swing, objects implementing the Receiver interface can register to be notified every time a Protocol Socket gets a line of input.
public class MyClass implements Receiver {
private final PorotocolSocket socket;
public void MyClass(){
socket = new ProtocolSocket("localhost", 12345);
socket.addReceiver(this);
}
public void receive(String input){
System.out.println("Got " + input + " from the socket.");
}
}
Every time the socket reads a line of input, it reports it to its receivers via Receiver#receive(String).
A full example can be found in:
Full documentation can be found here.
This software is freeware. Use it, abuse it, whatever! I always appreciate being mentioned if you are so inclined.
As always, they go to sgware@gmail.com.