For more information about vert.x please read the previous article from here.
Following is a simple http Server implemented using vert.x to understand the nature of vert.x applications.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io.vertx.core.AbstractVerticle; | |
import io.vertx.core.http.HttpServer; | |
import io.vertx.core.Handler; | |
import io.vertx.core.http.HttpServerRequest; | |
import io.vertx.core.http.HttpServerResponse; | |
import io.vertx.core.Verticle; | |
public class Server extends AbstractVerticle | |
{ | |
private HttpServer server = null; | |
@Override | |
public void start() throws Exception | |
{ | |
server = vertx.createHttpServer(); | |
server.requestHandler(new Handler<HttpServerRequest>() | |
{ | |
@Override | |
public void handle(HttpServerRequest request) | |
{ | |
System.out.println("Request received"); | |
HttpServerResponse response = request.response(); | |
response.setStatusCode(200); | |
response.headers() | |
.add("Content-Length", String.valueOf(57)) | |
.add("Content-Type", "text/html") | |
; | |
response.write("Hi " + (String)request.getParam("name")); | |
response.end(); | |
} | |
}); | |
server.listen(8500); | |
} | |
} |
To run the above http server, you need vert.x installed and setup properly.
To start the server, open a terminal or a command promt and run the following command.
vertx run Server.java
After you run the above command you will get a message saying 'Succeeded in deploying verticle'.
If you get any errors, please check your vert.x installation.
Now your server is running and waiting for requests to come.
Note that the above server is implemented to handle GET requests only. It listens to the port 8500.
As line 28 needs a parameter called "name", our GET request should include a name parameter.
Now open your browser, paste the below url and hit enter. For 'yourname', you can give anything.
http://localhost:8500/?name=yourname

Now you've used successfully used vert.x to build a server.
This server can handle multiple clients at the same time although in the code we never do anything about it. And we don't have to worry about synchronization or deadlocks.
This is the speciality of vert.x.
This same server can be built using javaScript, ruby Groovy or Python to run on JVM.
More examples can be found in the official github repository of vert.x.
No comments:
Post a Comment