io.reactivex.netty.examples.http.wordcounter.README.md Maven / Gradle / Ivy
Overview
========
This is more complex POST example where custom RawContentSource class is implemented to stream a file content
to the server, which provides word counting service, and sends back number of counted words as a reply.
This example is a reverse of the [chunk](../chunk) example, where file content was sent from server to client, which performed
word counting operations on it.
Running
=======
To run the example execute:
```
$ cd RxNetty/rxnetty-examples
$ ../gradlew runWordCounterServer
```
and in another console:
```
$ cd RxNetty/rxnetty-examples
$ ../gradlew runWordCounterClient -PtextFile=
```
HTTP client
===========
Here is the snippet from [WordCounterClient](WordCounterClient.java):
```java
public int countWords() throws IOException {
PipelineConfigurator, HttpClientRequest> pipelineConfigurator
= PipelineConfigurators.httpClientConfigurator();
HttpClient client = RxNetty.createHttpClient("localhost", port, pipelineConfigurator);
HttpClientRequest request = HttpClientRequest.create(HttpMethod.POST, "test/post");
FileContentSource fileContentSource = new FileContentSource(new File(textFile));
request.withRawContentSource(fileContentSource);
WordCountAction wAction = new WordCountAction();
client.submit(request).toBlocking().forEach(wAction);
fileContentSource.close();
return wAction.wordCount;
}
```
WordCounterClient.FileContentSource class in the code above is a custom implementation of RawContentSource interface,
that reads text file in small chunks. It uses the RxNetty provided StringTransformer for String to ByteBuf converstion.
HTTP server
===========
Here is the snippet from [WordCounterServer](WordCounterServer.java):
```java
public HttpServer createServer() {
HttpServer server = RxNetty.createHttpServer(port, new RequestHandler() {
@Override
public Observable handle(HttpServerRequest request, final HttpServerResponse response) {
return request.getContent()
.map(new Func1() {
@Override
public String call(ByteBuf content) {
return content.toString(Charset.defaultCharset());
}
})
.lift(new WordSplitOperator())
.count()
.flatMap(new Func1>() {
@Override
public Observable call(Integer counter) {
response.writeString(counter.toString());
return response.close();
}
});
}
});
System.out.println("Started word counter server...");
return server;
}
```
The server is doing simple word splitting/counting similarly to the [chunk](../chunk) example.