导航菜单

页面标题

页面副标题

Share Any v2.1.7 - CoolSocket.java 源代码

正在查看: Share Any v2.1.7 应用的 CoolSocket.java JAVA 源代码文件

本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。


package com.genonbeta.CoolSocket;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.Thread;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;
import je.c;

public abstract class CoolSocket {
    public static final String HEADER_ITEM_LENGTH = "length";
    public static final String HEADER_SEPARATOR = "\nHEADER_END\n";
    public static final int NO_TIMEOUT = -1;
    public static final String TAG = "CoolSocket";
    private final ArrayList<ActiveConnection> mConnections;
    private ExecutorService mExecutor;
    private int mMaxConnections;
    private ServerSocket mServerSocket;
    private Thread mServerThread;
    private SocketAddress mSocketAddress;
    private ServerRunnable mSocketRunnable;
    private int mSocketTimeout;

    public static class ActiveConnection {
        private int mId;
        private Socket mSocket;
        private int mTimeout;

        public class Response {
            public c headerIndex;
            public SocketAddress remoteAddress;
            public String response;
            public long totalLength = -1;

            public Response() {
            }
        }

        public ActiveConnection() {
            this(new Socket());
        }

        public ActiveConnection(int i10) {
            this(new Socket(), i10);
        }

        public ActiveConnection(Socket socket) {
            this.mTimeout = -1;
            this.mId = getClass().hashCode();
            this.mSocket = socket;
        }

        public ActiveConnection(Socket socket, int i10) {
            this(socket);
            setTimeout(i10);
        }

        public ActiveConnection connect(SocketAddress socketAddress) {
            if (getTimeout() != -1) {
                getSocket().setSoTimeout(getTimeout());
            }
            getSocket().bind(null);
            getSocket().connect(socketAddress);
            return this;
        }

        public boolean equals(Object obj) {
            return obj instanceof ActiveConnection ? obj.toString().equals(toString()) : super.equals(obj);
        }

        @Deprecated
        public void finalize() {
            super.finalize();
            if (getSocket() == null || getSocket().isClosed()) {
                return;
            }
            System.out.println(CoolSocket.TAG + ": Connections should be closed before their references are being destroyed");
            getSocket().close();
        }

        public InetAddress getAddress() {
            return getSocket().getInetAddress();
        }

        public String getClientAddress() {
            return getAddress().getHostAddress();
        }

        public int getId() {
            return this.mId;
        }

        public Socket getSocket() {
            return this.mSocket;
        }

        public int getTimeout() {
            return this.mTimeout;
        }

        public Response receive() {
            byte[] bArr = new byte[8096];
            long currentTimeMillis = getTimeout() != -1 ? System.currentTimeMillis() + getTimeout() : -1L;
            InputStream inputStream = getSocket().getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ByteArrayOutputStream byteArrayOutputStream2 = new ByteArrayOutputStream();
            Response response = new Response();
            response.remoteAddress = getSocket().getRemoteSocketAddress();
            do {
                int read = inputStream.read(bArr);
                if (read > 0) {
                    if (response.totalLength != -1) {
                        byteArrayOutputStream2.write(bArr, 0, read);
                        byteArrayOutputStream2.flush();
                    } else {
                        byteArrayOutputStream.write(bArr, 0, read);
                        byteArrayOutputStream.flush();
                        if (byteArrayOutputStream.toString().contains(CoolSocket.HEADER_SEPARATOR)) {
                            String byteArrayOutputStream3 = byteArrayOutputStream.toString();
                            int indexOf = byteArrayOutputStream3.indexOf(CoolSocket.HEADER_SEPARATOR);
                            c cVar = new c(byteArrayOutputStream3.substring(0, indexOf));
                            response.totalLength = cVar.g(CoolSocket.HEADER_ITEM_LENGTH);
                            response.headerIndex = cVar;
                            if (indexOf < byteArrayOutputStream.size()) {
                                byteArrayOutputStream2.write(byteArrayOutputStream3.substring(indexOf + 12).getBytes());
                            }
                        }
                    }
                }
                if (currentTimeMillis != -1 && System.currentTimeMillis() > currentTimeMillis) {
                    throw new TimeoutException("Read timed out!");
                }
                if (response.totalLength == byteArrayOutputStream2.size()) {
                    break;
                }
            } while (response.totalLength != 0);
            response.response = byteArrayOutputStream2.toString();
            return response;
        }

        public void reply(String str) {
            int read;
            byte[] bytes = str == null ? new byte[0] : str.getBytes();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            PrintWriter printWriter = new PrintWriter(byteArrayOutputStream);
            c cVar = new c();
            cVar.A(CoolSocket.HEADER_ITEM_LENGTH, Integer.valueOf(bytes.length));
            printWriter.write(cVar.toString() + CoolSocket.HEADER_SEPARATOR);
            printWriter.flush();
            byte[] bArr = new byte[8096];
            long currentTimeMillis = getTimeout() != -1 ? System.currentTimeMillis() + getTimeout() : -1L;
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            DataOutputStream dataOutputStream = new DataOutputStream(getSocket().getOutputStream());
            dataOutputStream.write(byteArrayOutputStream.toByteArray());
            dataOutputStream.flush();
            do {
                read = byteArrayInputStream.read(bArr);
                if (read > 0) {
                    dataOutputStream.write(bArr, 0, read);
                }
                if (currentTimeMillis != -1 && System.currentTimeMillis() > currentTimeMillis) {
                    throw new TimeoutException("Read timed out!");
                }
            } while (read != -1);
        }

        public void setId(int i10) {
            this.mId = i10;
        }

        public void setTimeout(int i10) {
            this.mTimeout = i10;
        }
    }

    public static class Client {
        private Object mReturn;

        public interface ConnectionHandler {
            void onConnect(Client client);
        }

        public ActiveConnection connect(SocketAddress socketAddress, int i10) {
            return new ActiveConnection(i10).connect(socketAddress);
        }

        public void connect(ActiveConnection activeConnection, SocketAddress socketAddress) {
            activeConnection.connect(socketAddress);
        }

        public Object getReturn() {
            return this.mReturn;
        }

        public void setReturn(Object obj) {
            this.mReturn = obj;
        }
    }

    public class ServerRunnable implements Runnable {
        private ServerRunnable() {
        }

        @Override
        public void run() {
            try {
                try {
                    CoolSocket.this.onServerStarted();
                    do {
                        Socket accept = CoolSocket.this.getServerSocket().accept();
                        if (CoolSocket.this.isInterrupted()) {
                            accept.close();
                        } else {
                            CoolSocket.this.respondRequest(accept);
                        }
                    } while (!CoolSocket.this.isInterrupted());
                } catch (IOException e10) {
                    CoolSocket.this.onInternalError(e10);
                }
            } finally {
                CoolSocket.this.onServerStopped();
            }
        }
    }

    public CoolSocket() {
        this.mConnections = new ArrayList<>();
        this.mSocketAddress = null;
        this.mSocketTimeout = -1;
        this.mMaxConnections = 10;
        this.mSocketRunnable = new ServerRunnable();
    }

    public CoolSocket(int i10) {
        this.mConnections = new ArrayList<>();
        this.mSocketAddress = null;
        this.mSocketTimeout = -1;
        this.mMaxConnections = 10;
        this.mSocketRunnable = new ServerRunnable();
        this.mSocketAddress = new InetSocketAddress(i10);
    }

    public CoolSocket(String str, int i10) {
        this.mConnections = new ArrayList<>();
        this.mSocketAddress = null;
        this.mSocketTimeout = -1;
        this.mMaxConnections = 10;
        this.mSocketRunnable = new ServerRunnable();
        this.mSocketAddress = new InetSocketAddress(str, i10);
    }

    public static <T> T connect(Client.ConnectionHandler connectionHandler, Class<T> cls) {
        Client client = new Client();
        connectionHandler.onConnect(client);
        if (client.getReturn() == null || cls == null) {
            return null;
        }
        return cls.cast(client.getReturn());
    }

    public static void connect(final Client.ConnectionHandler connectionHandler) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                CoolSocket.connect(Client.ConnectionHandler.this, null);
            }
        }.start();
    }

    public int getConnectionCountByAddress(InetAddress inetAddress) {
        Iterator<ActiveConnection> it = getConnections().iterator();
        int i10 = 0;
        while (it.hasNext()) {
            if (it.next().getAddress().equals(inetAddress)) {
                i10++;
            }
        }
        return i10;
    }

    public synchronized List<ActiveConnection> getConnections() {
        return this.mConnections;
    }

    public ExecutorService getExecutor() {
        if (this.mExecutor == null) {
            this.mExecutor = Executors.newFixedThreadPool(this.mMaxConnections);
        }
        return this.mExecutor;
    }

    public int getLocalPort() {
        return getServerSocket().getLocalPort();
    }

    public ServerSocket getServerSocket() {
        return this.mServerSocket;
    }

    public Thread getServerThread() {
        return this.mServerThread;
    }

    public SocketAddress getSocketAddress() {
        return this.mSocketAddress;
    }

    public ServerRunnable getSocketRunnable() {
        return this.mSocketRunnable;
    }

    public int getSocketTimeout() {
        return this.mSocketTimeout;
    }

    public boolean isComponentsReady() {
        return (getServerSocket() == null || getServerThread() == null || getSocketAddress() == null) ? false : true;
    }

    public boolean isInterrupted() {
        return getServerThread() == null || getServerThread().isInterrupted();
    }

    public boolean isServerAlive() {
        return getServerThread() != null && getServerThread().isAlive();
    }

    public abstract void onConnected(ActiveConnection activeConnection);

    public void onInternalError(Exception exc) {
    }

    public void onServerStarted() {
    }

    public void onServerStopped() {
    }

    public boolean respondRequest(final Socket socket) {
        int size = getConnections().size();
        int i10 = this.mMaxConnections;
        if (size > i10 && i10 != 0) {
            return false;
        }
        final ActiveConnection activeConnection = new ActiveConnection(socket, this.mSocketTimeout);
        synchronized (getConnections()) {
            getConnections().add(activeConnection);
        }
        getExecutor().submit(new Runnable() {
            @Override
            public void run() {
                try {
                    if (CoolSocket.this.mSocketTimeout > -1) {
                        activeConnection.getSocket().setSoTimeout(CoolSocket.this.mSocketTimeout);
                    }
                } catch (SocketException e10) {
                    e10.printStackTrace();
                }
                CoolSocket.this.onConnected(activeConnection);
                try {
                    try {
                        if (!socket.isClosed()) {
                            System.out.println(CoolSocket.TAG + ": You should close connections in the end of onConnected(ActiveConnection) method");
                            socket.close();
                        }
                        synchronized (CoolSocket.this.getConnections()) {
                            CoolSocket.this.getConnections().remove(activeConnection);
                        }
                    } catch (Throwable th) {
                        synchronized (CoolSocket.this.getConnections()) {
                            CoolSocket.this.getConnections().remove(activeConnection);
                            throw th;
                        }
                    }
                } catch (IOException e11) {
                    e11.printStackTrace();
                    synchronized (CoolSocket.this.getConnections()) {
                        CoolSocket.this.getConnections().remove(activeConnection);
                    }
                }
            }
        });
        return true;
    }

    public void setExecutor(ExecutorService executorService) {
        this.mExecutor = executorService;
    }

    public void setMaxConnections(int i10) {
        this.mMaxConnections = i10;
    }

    public void setSocketAddress(SocketAddress socketAddress) {
        this.mSocketAddress = socketAddress;
    }

    public void setSocketTimeout(int i10) {
        this.mSocketTimeout = i10;
    }

    public boolean start() {
        if (getServerSocket() == null || getServerSocket().isClosed()) {
            try {
                this.mServerSocket = new ServerSocket();
                getServerSocket().bind(this.mSocketAddress);
            } catch (IOException e10) {
                e10.printStackTrace();
                return false;
            }
        }
        if (getServerThread() == null || Thread.State.TERMINATED.equals(getServerThread().getState())) {
            this.mServerThread = new Thread(getSocketRunnable());
            getServerThread().setDaemon(true);
            getServerThread().setName(TAG + " Main Thread");
        } else if (getServerThread().isAlive()) {
            return false;
        }
        getServerThread().start();
        return true;
    }

    public boolean startDelayed(int i10) {
        long currentTimeMillis = System.currentTimeMillis();
        while (isServerAlive()) {
            if (System.currentTimeMillis() - currentTimeMillis > i10) {
                return false;
            }
        }
        return start();
    }

    public boolean startEnsured(int i10) {
        long currentTimeMillis = System.currentTimeMillis();
        if (!startDelayed(i10)) {
            return false;
        }
        while (!isServerAlive()) {
            if (System.currentTimeMillis() - currentTimeMillis > i10) {
                return false;
            }
        }
        return true;
    }

    public boolean stop() {
        if (isInterrupted()) {
            return false;
        }
        getServerThread().interrupt();
        if (getServerSocket().isClosed()) {
            return true;
        }
        try {
            getServerSocket().close();
            return true;
        } catch (IOException e10) {
            e10.printStackTrace();
            return true;
        }
    }
}