Download IMC (Implementing Mobile Calculi)

Transcript
public GenericClientConsole(String host) throws ProtocolException, IOException {
SessionStarterTable sessionStarterTable = new IMCSessionStarterTable();
SessionId sessionId = SessionId.parseSessionId(host);
System.out.println("creating session " + sessionId + " ...");
ProtocolStack protocolStack = new ProtocolStack();
Session session = protocolStack.connect(sessionStarterTable.createSessionStarter(sessionId));
System.out.println("established session " + session);
// start the thread that reads answers
new ReceiverThread(protocolStack).start();
UnMarshaler console = new IMCUnMarshaler(System.in);
System.out.println("insert message terminated by a line containing only one .");
while (true) {
StringBuffer stringBuffer = new StringBuffer();
while (true) {
String line = console.readStringLine();
if (line.equals("."))
break;
stringBuffer.append(line + "\n");
}
Marshaler marshaler = protocolStack.createMarshaler();
marshaler.writeBytes(stringBuffer.toString());
protocolStack.releaseMarshaler(marshaler);
}
}
public static void main(String[] args) throws ProtocolException, IOException {
String host = "tcp" + SessionId.PROTO_SEPARATOR + "localhost:9999";
if (args.length > 0)
host = args[0];
new GenericClientConsole(host);
}
}
Notice that the ReceiverThread obtains a new unmarshaler each time it does not find any more
bytes to read from the unmarshaler. This makes it work smoothly both over TCP and UDP: as
hinted before, in the former case the unmarshaler returned by createUnMarshaler() is always
the same, and in the latter a new unmarshaler is returned only when a new DatagramPacket is
received.
Now we can run the server of Example 4.5 in “UDP mode” and test it with our client as follows:
java examples.protocol.GenericClientConsole udp-localhost:9999
creating session udp-localhost:9999 ...
established session udp-127.0.0.1:1026->udp-localhost:9999
insert message terminated by a line containing only one .
WRITE
Hello World!
.
OK
READ
.
Hello World!
2
26