Java Reference
In-Depth Information
You can think of a Verticle as being a bit like a Servlet —it's the atomic unit of deploy-
ment in the Vert.x framework. The entry point to the code is the start method, which is a bit
like a main method in a regular Java program. In our chat app, we just use it to set up a serv-
er that accepts TCP connections.
We pass in a lambda expression to the connectHandler method, which gets called whenever
someone connects to our chat app. This is a callback and works in a similar way to the Swing
callbacks I talked about way back in Chapter 1 . The benefit of this approach is that the ap-
plication doesn't control the threading model—the Vert.x framework can deal with managing
threads and all the associated complexity, and all we need to do is think in terms of events
and callbacks.
Our application registers another callback using the dataHandler method. This is a callback
that gets called whenever some data is read from the socket. In this case, we want to provide
more complex functionality, so instead of passing in a lambda expression we use a regular
class, User , and let it implement the necessary functional interface. The callback into our
User class is listed in Example 9-2 .
Example 9-2. Handling user connections
public class
class User
User implements
implements Handler < Buffer > {
private static
static final
final Pattern newline = Pattern . compile ( "\\n" );
private final
final NetSocket socket ;
private final
final Set < String > names ;
private final
final EventBus eventBus ;
private Optional < String > name ;
public User ( NetSocket socket , Verticle verticle ) {
Vertx vertx = verticle . getVertx ();
this . socket = socket ;
names = vertx . sharedData (). getSet ( "names" );
eventBus = vertx . eventBus ();
name = Optional . empty ();
public void
void handle ( Buffer buffer ) {
newline . splitAsStream ( buffer . toString ())
. forEach ( line -> {
Search WWH ::

Custom Search