|
@@ -0,0 +1,83 @@
|
|
|
+package com.scbfkj.uni.process;
|
|
|
+
|
|
|
+import org.apache.commons.pool2.BaseKeyedPooledObjectFactory;
|
|
|
+import org.apache.commons.pool2.KeyedObjectPool;
|
|
|
+import org.apache.commons.pool2.PooledObject;
|
|
|
+import org.apache.commons.pool2.impl.DefaultPooledObject;
|
|
|
+import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
|
|
|
+
|
|
|
+import java.io.*;
|
|
|
+import java.net.*;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.Hashtable;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Map;
|
|
|
+
|
|
|
+public class SocketClient {
|
|
|
+
|
|
|
+
|
|
|
+ private static final Map<String, Socket> sockets = new Hashtable<>();
|
|
|
+
|
|
|
+
|
|
|
+ public void sendMessage(String url, List<String> messages, Long timeOut) throws Exception {
|
|
|
+
|
|
|
+ Socket socket = sockets.get(url);
|
|
|
+ if (socket == null || socket.isClosed()) {
|
|
|
+ socket = getSocket(url, timeOut);
|
|
|
+ }
|
|
|
+
|
|
|
+ try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));) {
|
|
|
+
|
|
|
+ for (String message : messages) {
|
|
|
+
|
|
|
+ writer.write(message);
|
|
|
+ writer.newLine();
|
|
|
+ }
|
|
|
+ writer.flush();
|
|
|
+ } catch (IOException e) {
|
|
|
+ System.err.println("Error in client: " + e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public List<String> receptionMessage(String url, Long pollSize, Long timeOut) throws Exception {
|
|
|
+
|
|
|
+ Socket socket = sockets.get(url);
|
|
|
+ if (socket == null || socket.isClosed()) {
|
|
|
+ socket = getSocket(url, timeOut);
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+ List<String> result = new ArrayList<>();
|
|
|
+ try (
|
|
|
+ BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
|
|
|
+ while (true) {
|
|
|
+
|
|
|
+ String value = reader.readLine();
|
|
|
+ if (value == null) {
|
|
|
+ break;
|
|
|
+ } else {
|
|
|
+ result.add(value);
|
|
|
+ if (result.size() == pollSize) {
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } catch (SocketTimeoutException e) {
|
|
|
+ return result;
|
|
|
+ } catch (IOException e) {
|
|
|
+ System.err.println("Error in client: " + e.getMessage());
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ private Socket getSocket(String url, Long timeOut) throws IOException {
|
|
|
+ Socket socket;
|
|
|
+ String[] strings = url.split(":");
|
|
|
+ String host = strings[0];
|
|
|
+ String port = strings[1];
|
|
|
+ socket = new Socket(host, Integer.parseInt(port));
|
|
|
+ socket.setSoTimeout(timeOut.intValue());
|
|
|
+ sockets.put(url, socket);
|
|
|
+ return socket;
|
|
|
+ }
|
|
|
+}
|