Java tutorial
/* Copyright 2017 Mountain Fog, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.mtnfog.idyl.e3.sdk; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import java.net.UnknownHostException; import org.apache.commons.io.IOUtils; import com.google.gson.Gson; import com.mtnfog.idyl.e3.sdk.model.EntityExtractionResponse; import com.mtnfog.idyl.e3.sdk.model.StreamingClient; /** * Implementation of {@link StreamingClient} that uses a socket connection for * streaming text. * * @author Mountain Fog, Inc. * */ public class IdylE3StreamingClient implements StreamingClient { private Socket socket; private Gson gson; /** * Creates a new streaming client. * * @param server * The address of the Idyl E3 server. * @param port * The streaming port. * @throws UnknownHostException * Thrown if the host is invalid. * @throws IOException * Thrown if the socket connection cannot be opened. */ public IdylE3StreamingClient(String server, int port) throws UnknownHostException, IOException { socket = new Socket(server, port); gson = new Gson(); } @Override public EntityExtractionResponse stream(final String text) throws IOException { if (socket.isClosed()) { throw new IllegalStateException("The socket is closed."); } PrintStream out = new PrintStream(socket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out.print(text); String json = in.readLine(); System.out.println(json); in.close(); out.close(); return gson.fromJson(json, EntityExtractionResponse.class); } @Override public void close() { IOUtils.closeQuietly(socket); } }