Java Reference
In-Depth Information
iif (! name . isPresent ())
setName ( line );
else
handleMessage ( line );
});
}
// Class continues...
The buffer contains the data that has been written down the network connection to us.
We're using a newline-separated, text-based protocol, so we want to convert this to a String
and then split it based upon those newlines.
We have a regular expression to match newline characters, which is a
java.util.regex.Pattern instance called newline . Conveniently, Java's Pattern class
has had a splitAsStream method added in Java 8 that lets us split a String using the regu-
lar expression and have a stream of values, consisting of the values between each split.
The first thing our users do when they connect to our chat server is set their names. If we
don't know the user's name , then we delegate to the logic for setting the name; otherwise, we
handle our message like a normal chat message.
We also need a way of receiving messages from other users and passing them on to our chat
client so the recipients can read them. In order to implement this, at the same time that we set
the name of the current user we also register another callback that writes these messages
( Example 9-3 ) .
Example 9-3. Registering for chat messages
eventBus . registerHandler ( name , ( Message < String > msg ) -> {
sendClient ( msg . body ());
});
This code is actually taking advantage of Vert.x's event bus , which allows us to send mes-
sages between verticles in a nonblocking fashion (see Figure 9-1 ) . The registerHandler
method allows us to associate a handler with a certain address, so when a message is sent to
that address the handler gets called with the message as its argument. Here we use the user-
name as the address.
Search WWH ::




Custom Search