Android 使用Socket实现服务器与手机客户端的长连接五:使用队列封装请求

一、概述:

1、把发送者发送的信息全部封装在blockqueue队列里,然后使用connManager把队列里的信息取出,分发出去
2、原理图:
这里写图片描述

二、实现:

/**
 * @描述 使用socket实现长连接
 * @项目名称 App_Chat
 * @包名 com.android.chat.utils
 * @类名 TcpUtil
 * @author chenlin
 * @date 2012年6月26日 下午4:06:43
 * @version 1.0
 */
public class ConnManager {
    protected static final int STATE_FROM_SERVER_OK = 0;
    private static String dsName = "192.168.31.239";
    private static int dstPort = 10002;
    private static Socket socket;
    //队列,封装发送的信息
    private static ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(8);

    private static ConnManager instance;

    private ConnManager() {
    }

    public static ConnManager getInstance() {
        if (instance == null) {
            synchronized (ConnManager.class) {
                if (instance == null) {
                    instance = new ConnManager();
                }
            }
        }
        return instance;
    }

    /**
     * 连接
     * 
     * @return
     */
    public boolean connect(final Handler handler) {

        if (socket == null || socket.isClosed()) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    try {
                        socket = new Socket(dsName, dstPort);
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        throw new RuntimeException("连接错误: " + e.getMessage());
                    }

                    new Thread(new RequestWorker()).start();

                    try {
                        // 输入流,为了获取客户端发送的数据
                        InputStream is = socket.getInputStream();
                        byte[] buffer = new byte[1024];
                        int len = -1;
                        while ((len = is.read(buffer)) != -1) {
                            final String result = new String(buffer, 0, len);

                            Message msg = Message.obtain();
                            msg.obj = result;
                            msg.what = STATE_FROM_SERVER_OK;
                            handler.sendMessage(msg);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException("getInputStream错误: " + e.getMessage());
                    }

                }
            }).start();
        }

        return true;
    }

    /**
     * 连接
     * 
     * @return
     */
    public void connect() {
        if (socket == null || socket.isClosed()) {

            try {
                socket = new Socket(dsName, dstPort);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                throw new RuntimeException("连接错误: " + e.getMessage());
            }

            try {
                // 输入流,为了获取客户端发送的数据
                InputStream is = socket.getInputStream();
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = is.read(buffer)) != -1) {
                    final String result = new String(buffer, 0, len);
                    if (mListener !=null) {
                        mListener.pushData(result);
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException("getInputStream错误: " + e.getMessage());
            }

        }

    }

    /**
     * 添加请求
     * @param content
     */
    public void putRequest(String content) {
        try {
            queue.put(content);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送信息
     * 
     * @param auth
     */
    public void sendAuth(String auth) {
        OutputStream os = null;
        try {
            if (socket != null) {
                os = socket.getOutputStream();
                os.write(auth.getBytes());
                os.flush();
            }
        } catch (IOException e) {
            throw new RuntimeException("发送失败:" + e.getMessage());
        }
    }

    /**
     * 关闭连接
     */
    public void disConnect() {
        if (socket != null && !socket.isClosed()) {
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException("关闭异常:" + e.getMessage());
            }
            socket = null;
        }
    }


    public class RequestWorker implements Runnable{
        @Override
        public void run() {
            OutputStream os = null;
            try {
                if (socket != null) {
                    os = socket.getOutputStream();
                    //take是个阻塞式方法,所以必须是用while(true)
                    while(true){
                        String content = queue.take();
                        os.write(content.getBytes());
                        os.flush();
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException("发送失败:" + e.getMessage());
            } catch (InterruptedException e) {
                throw new RuntimeException("信息被中断:" + e.getMessage());
            }
        }
    }

    public  interface  ConnectionListener{
        void pushData(String str);
    }
    private ConnectionListener mListener;
    public void setConnectionListener(ConnectionListener listener){
        this.mListener = listener;
    }
}

———————————————————————
(java 架构师全套教程,共760G, 让你从零到架构师,每月轻松拿3万)
有需求者请进站查看,非诚勿扰

https://item.taobao.com/item.htm?spm=686.1000925.0.0.4a155084hc8wek&id=555888526201

01.高级架构师四十二个阶段高
02.Java高级系统培训架构课程148课时
03.Java高级互联网架构师课程
04.Java互联网架构Netty、Nio、Mina等-视频教程
05.Java高级架构设计2016整理-视频教程
06.架构师基础、高级片
07.Java架构师必修linux运维系列课程
08.Java高级系统培训架构课程116课时
(送:hadoop系列教程,java设计模式与数据结构, Spring Cloud微服务, SpringBoot入门)
——————————————————————–

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lovoo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值