Skip to content

Instantly share code, notes, and snippets.

@BrunoBonacci
Created July 1, 2012 14:22
Show Gist options
  • Save BrunoBonacci/3028571 to your computer and use it in GitHub Desktop.
Save BrunoBonacci/3028571 to your computer and use it in GitHub Desktop.
Vert.x Simple Telnet Server - NIO Server
// general configuration
settings = [port: 1234];
// Vert.x server and event-bus
def server = vertx.createNetServer()
def bus = vertx.eventBus
// Connection handler. Here requests are captured, parsed, and executed.
server.connectHandler { sock ->
// upon a new connection, assigning a new connection id (cid)
String cid = registerConnection();
println "[$cid]# got a new connection id: $cid - currently ${_connections.size()} are alive.";
// welcome the user with a message
sock.write(welcome())
// handle the connection close.
sock.closedHandler {
_connections.remove(cid);
println "[$cid]# The connection is now closed"
}
// handle incoming requests from a single connection
// a request, might contains multiple commands, splitting them by line.
sock.dataHandler { buffer ->
def lines = new String(buffer.bytes).trim().split("\r\n").collect { it.trim() }
lines.each {
println "[$cid]> $it"
if (it == "") return
// if a command is found send it to the commands-handler
bus.send("commands", [command: it, cid: cid]) {
resp ->
// once you get a response for a command
// then send it back to the user
String outMessage = prepareOutput(resp.body.message)
if (outMessage != "") {
sock.write("$outMessage\r\n") {
println "[$cid]< " + outMessage.replaceAll("\n", "\n[$cid]< ")
}
}
// if the command was "quit", close the connection.
if (resp.body.status == "ACTION" && resp.body.action == "QUIT")
sock.close()
}
}
}
}.listen( settings.port );
println """
---------------------------------------------------------------------
Simple Vert.x Telnet Server
---------------------------------------------------------------------
(*) Server started at $BASE_DIR and listening on port: $settings.port
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment