Java Socket Tcp 完整示例

/**

 * 设置监听

 *

 * @param socketCallback

 */

public void setSocketCallback(TcpSocketCallback socketCallback) {

    this.mTcpSocketCallback = socketCallback;

}



public SocketClient() {



}



final Object LOCK = new Object();



public void startTcpSocket(final String ip, int port) {

    ThreadPool.getInstance().execute(new Runnable() {

        @Override

        public void run() {



            // 确保一个连接操作。

            synchronized (LOCK) {



                if (isConnection())

                    return;



                if (startTcpConnection(ip, port)) {// 尝试建立 TCP 连接

                    startReceiveTcpThread();

                    LogWrapper.d(TAG, "连接成功");

                    if (mTcpSocketCallback != null)

                        mTcpSocketCallback.onConnect(ip, port);

                } else {

                    LogWrapper.d(TAG, "连接失败, 开始断开...");

                    disConnect();

                }



            }

        }

    });

}





private final Object LOCKS = new Object();



/**

 * 创建接收线程

 */

private void startReceiveTcpThread() {

    ThreadPool.getInstance().execute(new Runnable() {

        @Override

        public void run() {

            try {

                while (true) {

                    synchronized (LOCKS) {

                        byte[] srcType = new byte[4];

                        is.read(srcType);

                        int type = BytesUtils.bytes2Int(srcType);



                        byte[] src = new byte[4];

                        is.read(src);

                        int len = BytesUtils.bytes2Int(src);



                        byte[] srcData = new byte[len];

                        is.read(srcData);



                        if (type == SocketConfig.SOCKET_STRING) {

                            String str = new String(srcData);

                            if (mTcpSocketCallback != null)

                                mTcpSocketCallback.onReceived(str);

                        } else if (type == SocketConfig.SOCKET_BYTE) {

                            if (mTcpSocketCallback != null)

                                mTcpSocketCallback.onReceived(srcData);

                        }

                    }



                }

            } catch (IOException e) {

                e.printStackTrace();

                // 没有正常关闭时会出现

                LogWrapper.e(TAG, "接收消息异常, 开始断开...:" + e.toString());

                disConnect();

            }

        }

    });

}



/**

 * 处理 tcp 收到的消息

 *

 * @param line

 */

private void handleReceiveTcpMessage(String line) {

    LogWrapper.d(TAG, "接收 tcp 消息 长度:" + line);

    if (mTcpSocketCallback != null)

        mTcpSocketCallback.onReceived(line);

}



public void sendTcpMessage(String json, SendCallback sendCallback) {

    ThreadPool.getInstance().execute(new Runnable() {

        @Override

        public void run() {

            try {

                pw.println(json);

                if (sendCallback != null)

                    sendCallback.success();

            } catch (Exception e) {

                if (sendCallback != null)

                    sendCallback.failed();

            }

        }

    });



}





/**

 * 尝试建立tcp连接

 *

 * @param ip

 * @param port

 */

private boolean startTcpConnection(final String ip, final int port) {

    try {

        if (mSocket == null) {

            mSocket = new Socket(ip, port);

            mSocket.setKeepAlive(true);

            mSocket.setTcpNoDelay(true);

            mSocket.setReuseAddress(true);

            mSocket.setReceiveBufferSize(3000 * 1024);

        }

        is = mSocket.getInputStream();

        br = new BufferedReader(new InputStreamReader(is));

        OutputStream os = mSocket.getOutputStream();

        pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os)), true);

        LogWrapper.d(TAG, "tcp 创建成功...");

        return true;

    } catch (Exception e) {

        e.printStackTrace();

        LogWrapper.e(TAG, "startTcpConnection error:" + e.toString());

    }

    return false;

}



/**

 * 断开链接

 */

public void disConnect() {

    LogWrapper.d(TAG, "disConnect");

    try {

        if (is != null)

            is.close();



        // 要先关闭流,不然会阻塞

        if (br != null) {

            br.close();

        }



        if (pw != null) {

            pw.close();

        }

        if (mSocket != null) {

            mSocket.close();

            mSocket = null;

        }



        // 通知上层应用

        if (mTcpSocketCallback != null)

            mTcpSocketCallback.onDisConnect();



    } catch (IOException e) {

        e.printStackTrace();

        LogWrapper.e(TAG, "关闭socket出错:" + e.toString());

    }

}



/**

 * 连接的回调

 */

public interface TcpSocketCallback {



    void onConnect(String host, int port);



    void onDisConnect();



    void onReceived(String data);



    void onReceived(byte[] bytes);

}



/**

 * 发送的回调

 */

public interface SendCallback {

    void success();



    void failed();

}



/**

 * 是否是连接状态

 *

 * @return

 */

public boolean isConnection() {

    if (mSocket == null)

        return false;

    return !mSocket.isClosed() && mSocket.isConnected();

}

}




Server



import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.net.Socket;

public class SocketServerClient extends Thread {

private final String TAG = "SocketServerClient";



private Socket socket;

private OutputStream out;

private OnMessageListener listener;



public SocketServerClient(Socket socket, OnMessageListener listener) {

    this.socket = socket;

    this.listener = listener;

}



@Override

public void run() {

    while (true) {

        try {

            InputStream inputStream = socket.getInputStream();

            out = socket.getOutputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String str = reader.readLine();

            if (listener != null) {

                listener.onReceive(this, str);

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}



final Object LOCK = new Object();



public void sendBytes(final byte[] bytes) {

    new Thread(new Runnable() {

        @Override

        public void run() {

            synchronized (LOCK) {

                try {



                    if (bytes == null)

                        return;

                    //约定传输的类型 和 传输的长度

                    out.write(BytesUtils.int2ByteArray(SocketConfig.SOCKET_BYTE));

                    out.write(BytesUtils.int2ByteArray(bytes.length));

                    out.write(bytes);

                    out.flush();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }).start();

}



public void sendString(final String msg) {

    new Thread(new Runnable() {

        @Override

        public void run() {

            synchronized (LOCK) {

                try {



                    if (TextUtils.isEmpty(msg))

                        return;



                    String data = msg + "\n";

                    byte[] bytes = data.getBytes();

                    //约定传输的类型 和 传输的长度

                    out.write(BytesUtils.int2ByteArray(SocketConfig.SOCKET_STRING));

                    out.write(BytesUtils.int2ByteArray(bytes.length));

                    out.write(bytes);

                    out.flush();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }).start();

}





public interface OnMessageListener {

    void onReceive(SocketServerClient client, String str);

}

}


  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值