Socket通信工具类

Socket通信工具类

TCP客户端

public class TCPClientUtil {
    public static final String TAG = "Control";
    private Socket mSocket;
    private final ExecutorService mExecutorService;

    public TCPClientUtil(){
        mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    }

    public void startClient(final String address,final int port){
        if (address == null){
            return;
        }
        if (mSocket == null){
            Runnable mRunnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        Log.i(TAG,"TCP启动客户端成功");
                        mSocket = new Socket(address, port);
                        Log.i(TAG,"TCP客户端连接成功");

                        InputStream inputStream = mSocket.getInputStream();
                        byte[] buffer = new byte[1024];
                        int len = -1;
                        while ((len = inputStream.read(buffer))!=-1){
                            // 将读取到的数据复制到一个新的数组中
                            //String s = new String(buffer, 0, len);
                            byte[] data = Arrays.copyOfRange(buffer, 0, len);
                            mIMessageCallback.callback(data);
                            Log.i(TAG, "TCP收到服务器的数据-------:" + Arrays.toString(data));
                        }
                        mIServerDisConnect.callback();
                        Log.i(TAG,"TCP客户端断开连接");
                    } catch (Exception e) {
                        Log.e(TAG,"TCP 客户端无法连接服务器:"+e.getMessage());
                    } finally {
                        try {
                            if (mSocket != null){
                                mSocket.close();
                            }
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                        mSocket = null;
                    }
                }
            };
            mExecutorService.execute(mRunnable);
        }
    }

    public void sendTcpMessage(final byte[] msg){
        if (mSocket != null && mSocket.isConnected()){
            Runnable mRunnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        mSocket.getOutputStream().write(msg);
                        mSocket.getOutputStream().flush();
                        Log.i(TAG,"TCP客户端发送数据-------:"+ Arrays.toString(msg));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
            mExecutorService.execute(mRunnable);
        }
    }

    public boolean isConnect(){
        if (mSocket != null){
            return mSocket.isConnected();
        }else {
            return false;
        }
    }

    public void closeConnect() throws IOException {
        mSocket.close();
    }

    IServerDisConnect mIServerDisConnect;
    public interface IServerDisConnect{
        void callback();
    }

    public void setIServerDisConnect(IServerDisConnect serverDisConnect){
        this.mIServerDisConnect = serverDisConnect;
    }

    IMessageCallback mIMessageCallback;

    public interface IMessageCallback{
        void callback(byte[] bytes);
    }

    public void setIMessageCallback(IMessageCallback messageCallback){
        this.mIMessageCallback = messageCallback;
    }
}

TCP服务端

public class TCPServerUtil {
    public static final String TAG = "TCP";
    private ServerSocket mServerSocket;
    private ExecutorService mExecutorService;
    private Socket mSocket;

    public TCPServerUtil() {
        mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        try {
            Log.i("tcp", "启动服务端");
            mServerSocket = new ServerSocket(8989);
            Log.i("tcp", "服务端连接成功");
        } catch (Exception e) {
            Log.i("tcp", "启动服务端失败");
        }
    }

    public void startSever() {
        Runnable mRunnable = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        mSocket = mServerSocket.accept();
                        Log.i(TAG, mSocket.getRemoteSocketAddress().toString() + "");
                        InputStream inputStream = mSocket.getInputStream();

                        byte[] buffer = new byte[1024];
                        int len = -1;
                        while ((len = inputStream.read(buffer)) != -1) {
                            byte[] data = Arrays.copyOfRange(buffer, 0, len);
                            //String data = new String(buffer, 0, len);
                            mIMessageCallback.callback(data);
                            Log.i(TAG, "收到客户端的数据-------------------:" + data);
                        }
                        Log.i(TAG, "客户端断开连接");

                    } catch (Exception EE) {
                        EE.printStackTrace();
                        Log.i(TAG, "服务端无法连接服务器" + EE.getMessage());
                        break;

                    } finally {
                        try {
                            if (mServerSocket != null) {
                                mServerSocket.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        mServerSocket = null;
                    }
                }
            }
        };
        mExecutorService.execute(mRunnable);
    }

    public void sendTcpMessage(final byte[] msg) {
        Runnable mRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    mSocket.getOutputStream().write(msg);
                    mSocket.getOutputStream().flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        mExecutorService.execute(mRunnable);
    }

    public void des() {
        try {
            mServerSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public IMessageCallback mIMessageCallback;

    public interface IMessageCallback {
        void callback(byte[] data);
    }

    public void setIMessageCallback(IMessageCallback messageCallback) {
        this.mIMessageCallback = messageCallback;
    }
}

UDP客户端

ublic class UDPClientUtil {
    public static final String TAG = "Control";
    private DatagramSocket mDatagramSocket;
    private ExecutorService mExecutorService;
    private DatagramPacket sendPacket;
    private DatagramPacket receivePacket;
    private InetSocketAddress address;

    public UDPClientUtil() {
        mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    }

    public void startClient() {
        if (mDatagramSocket == null) {
            Runnable mRunnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        Log.i(TAG, "UDP启动客户端");
                        mDatagramSocket = new DatagramSocket(8989);//本机监听的端口
                        mDatagramSocket.setReuseAddress(true);
                        Log.i(TAG, "UDP客户端连接成功");

                        byte[] buffer = new byte[1024];
                        int len = -1;

                        while (true) {
                            receivePacket = new DatagramPacket(buffer, buffer.length);
                            mDatagramSocket.receive(receivePacket);
                            Log.i(TAG, receivePacket.getAddress().toString() + ":" + receivePacket.getPort());
                            byte[] data = Arrays.copyOfRange(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());
                            //String data = new String(receivePacket.getData(), 0, receivePacket.getData().length, "utf-8");//针对中文要采用utf-8
                            mIMessageCallback.callback(data);
                            Log.i(TAG, "收到UDP服务器的数据--------:" + Arrays.toString(data));
                        }
                        //Log.i(TAG, "客户端断开连接");
                    } catch (Exception e) {
                        Log.e(TAG,"UDP 客户端无法连接服务器:"+e.getMessage());
                    } finally {
                        try {
                            if (mDatagramSocket != null) {
                                mDatagramSocket.close();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        mDatagramSocket = null;
                    }
                }
            };
            mExecutorService.execute(mRunnable);
        }
    }

    /**
     * @param msg  要发送的数据
     * @param ip   目标IP地址
     * @param port 目标端口号
     */
    public void sendUdpMessage(final byte[] msg, final String ip, final int port) {
        if (mDatagramSocket != null) {
            Runnable mRunnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        sendPacket = new DatagramPacket(msg, msg.length, InetAddress.getByName(ip), port);
                        mDatagramSocket.send(sendPacket);
                        Log.i(TAG,"UDP客户端发送数据-------:"+ Arrays.toString(msg)+"向服务器发送"+ip+":"+port);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
            mExecutorService.execute(mRunnable);
        }
    }

    public boolean isConnect(){
        if (mDatagramSocket != null){
            return mDatagramSocket.isConnected();
        }else {
            return false;
        }
    }

    public void closeConnect(){
        mDatagramSocket.close();
    }

    IMessageCallback mIMessageCallback;

    public interface IMessageCallback {
        void callback(byte[] data);
    }

    public void setIMessageCallback(IMessageCallback messageCallback) {
        this.mIMessageCallback = messageCallback;
    }
}

UDP服务端

public class UDPServerUtil {
    public static final String TAG = "UDP";
    private DatagramSocket mDatagramSocket;
    private ExecutorService mExecutorService;
    private DatagramPacket sendPacket;
    private DatagramPacket receivePacket;


    public UDPServerUtil() {
        mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        try {
            Log.i(TAG, "启动服务端");
            mDatagramSocket = new DatagramSocket(8989);
            Log.i(TAG, "服务端连接成功");
        } catch (Exception e) {
            Log.i(TAG, "启动服务端失败");
        }
    }

    public void startClient() {
        Runnable mRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    receivePacket = new DatagramPacket(buffer, buffer.length);
                    while (true) {
                        mDatagramSocket.receive(receivePacket);
                        byte[] data = Arrays.copyOfRange(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());
                        //String data = new String(receivePacket.getData(), 0, buffer.length, "utf-8");//针对中文要采用utf-8
                        mIMessageCallback.callback(data);
                        Log.i(TAG, "收到服务器的数据-------------------:" + data);
                    }
                } catch (Exception EE) {
                    EE.printStackTrace();
                    Log.i(TAG, "客户端无法连接服务器" + EE.getMessage());

                } finally {
                    try {
                        if (mDatagramSocket != null) {
                            mDatagramSocket.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mDatagramSocket = null;
                }
            }
        };
        mExecutorService.execute(mRunnable);
    }

    public void sendTcpMessage(final byte[] msg, final String ip, final int port) {
        if (mDatagramSocket != null) {
            Runnable mRunnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        sendPacket = new DatagramPacket(msg, msg.length, InetAddress.getByName(ip), port);
                        mDatagramSocket.send(sendPacket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
            mExecutorService.execute(mRunnable);
        }
    }

    public void des() {
        try {
            mDatagramSocket.close();
        } catch (Exception e) {
            Log.i(TAG, e.toString());
        }
    }

    public IMessageCallback mIMessageCallback;

    public interface IMessageCallback {
        void callback(byte[] data);
    }

    public void setIMessageCallback(IMessageCallback messageCallback) {
        this.mIMessageCallback = messageCallback;
    }
}

posted on 2023-12-05 11:48  lxx007  阅读(37)  评论(0编辑  收藏  举报

导航