import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Socket通讯工具类 */ public class SocketUtil { // 线程池 private static final ExecutorService ThreadPool = Executors.newCachedThreadPool(); /** * 发送Socket消息 * * @param targetIP 目标IP * @param targetPort 目标端口 * @param msg 消息 * @param callback 回调 */ public static void sendSocketMsg(final String targetIP, final int targetPort, final byte[] msg, final SocketUtilCallback callback) { ThreadPool.execute(new Runnable() { @Override public void run() { try { // 建立Socket连接 Socket socket = new Socket(targetIP, targetPort); socket.setSoTimeout(1000 * 10); // 写消息 OutputStream out = socket.getOutputStream(); out.write(msg); out.flush(); // 读取消息返回 byte[] readBuffer = new byte[1024]; InputStream in = socket.getInputStream(); int size = in.read(readBuffer); byte[] readBytes = null; if (size != -1) { readBytes = new byte[size]; System.arraycopy(readBuffer, 0, readBytes, 0, size); } // 关闭流和Socket连接 in.close(); out.close(); socket.close(); // 执行发送成功回调 if (callback != null && readBytes != null) { callback.onSuccess(readBytes); } } catch (IOException e) { // 执行发送失败回调 if (callback != null) { callback.onError(e); } } } }); } /** * 回调 */ public interface SocketUtilCallback { void onSuccess(byte[] result); void onError(Exception e); } }