Java Reference
In-Depth Information
cycles may range from reading more data from another client to ticking over your Minecraft
server!
I've so far avoided presenting any code to show the ideas because the concept of blocking
versus nonblocking I/O can be implemented in a number of different ways in terms of the
API. The Java standard library presents a nonblocking I/O API in the form of NIO (New
I/O). The original version of NIO uses the concept of a Selector , which lets a thread man-
age multiple channels of communication, such as the network socket that's used to write to
your chat client.
This approach never proved particularly popular with Java developers and resulted in code
that was fairly hard to understand and debug. With the introduction of lambda expressions, it
becomes idiomatic to design and develop APIs that don't have these deficiencies.
Callbacks
To demonstrate the principles of this approach, we're going to implement a dead simple chat
application—no bells and no whistles. In this application, users can send and receive mes-
sages to and from each other. They are required to set names for themselves when they first
connect.
We're going to implement the chat application using the Vert.x framework and introduce the
necessary techniques as we go along. Let's start by writing some code that receives TCP con-
nections, as demonstrated in Example 9-1 .
Example 9-1. Receiving TCP connections
public
public class
class ChatVerticle
ChatVerticle extends
extends Verticle {
public
public void
void start () {
vertx . createNetServer ()
. connectHandler ( socket -> {
container . logger (). info ( "socket connected" );
socket . dataHandler ( new
new User ( socket , this
this ));
}). listen ( 10_000 );
container . logger (). info ( "ChatVerticle started" );
}
}
Search WWH ::




Custom Search