|
| 1 | +/* |
| 2 | + * Copyright 2017 Red Hat, Inc. |
| 3 | + * |
| 4 | + * Red Hat licenses this file to you under the Apache License, version 2.0 |
| 5 | + * (the "License"); you may not use this file except in compliance with the |
| 6 | + * License. You may obtain a copy of the License at: |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 12 | + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 | + * License for the specific language governing permissions and limitations |
| 14 | + * under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package io.vertx.example.reactivex.net.greeter; |
| 18 | + |
| 19 | +import io.vertx.core.AbstractVerticle; |
| 20 | +import io.vertx.core.net.NetSocket; |
| 21 | +import io.vertx.core.parsetools.RecordParser; |
| 22 | +import io.vertx.example.util.Runner; |
| 23 | +import io.vertx.reactivex.FlowableHelper; |
| 24 | + |
| 25 | +import java.util.stream.Stream; |
| 26 | + |
| 27 | +/* |
| 28 | + * @author Thomas Segismont |
| 29 | + */ |
| 30 | +public class Client extends AbstractVerticle { |
| 31 | + |
| 32 | + // Convenience method so you can run it in your IDE |
| 33 | + public static void main(String[] args) { |
| 34 | + Runner.runExample(Client.class); |
| 35 | + } |
| 36 | + |
| 37 | + @Override |
| 38 | + public void start() throws Exception { |
| 39 | + vertx.createNetClient().connect(1234, "localhost", res -> { |
| 40 | + |
| 41 | + if (res.succeeded()) { |
| 42 | + NetSocket socket = res.result(); |
| 43 | + |
| 44 | + RecordParser parser = RecordParser.newDelimited("\n", socket); |
| 45 | + |
| 46 | + FlowableHelper.toFlowable(parser) |
| 47 | + .map(buffer -> buffer.toString("UTF-8")) |
| 48 | + .subscribe(greeting -> System.out.println("Net client receiving: " + greeting), t -> { |
| 49 | + t.printStackTrace(); |
| 50 | + socket.close(); |
| 51 | + }, socket::close); |
| 52 | + |
| 53 | + // Now send some data |
| 54 | + Stream.of("John", "Joe", "Lisa", "Bill").forEach(name -> { |
| 55 | + System.out.println("Net client sending: " + name); |
| 56 | + socket.write(name).write("\n"); |
| 57 | + }); |
| 58 | + |
| 59 | + } else { |
| 60 | + System.out.println("Failed to connect " + res.cause()); |
| 61 | + } |
| 62 | + }); |
| 63 | + } |
| 64 | +} |
0 commit comments