Android 使用Socket实现服务器与手机客户端的长连接八

一、发送请求的信息:

1、接口

 public interface Request {
    String getData();
}

2、文本请求:

public class TextRequest implements Request{
    private Map<String, String> map = new HashMap<String, String>();

    public TextRequest(String sender, String token, String receiver, String content) {
        map.put("type", "request");
        map.put("sequence", UUID.randomUUID().toString());
        map.put("action", "text");
        map.put("sender", sender);
        map.put("token", token);
        map.put("receiver", receiver);
        map.put("content", content);
    }

    @Override
    public String getData() {
        return new Gson().toJson(map);
    }
}

3、认证请求:

public class AuthRequest implements Request{
    private Map<String, String> map = new HashMap<String, String>();

    public AuthRequest(String sender, String token){
        map.put("type", "request");
        map.put("sequence", UUID.randomUUID().toString());
        map.put("action", "auth");
        map.put("sender", sender);
        map.put("token", token);
    }

    @Override
    public String getData() {
        return new Gson().toJson(map);
    }

} 

二、创建连接器

public class Connector {
    protected static final String dstName = "192.168.0.20";
    protected static final int dstPort = 9999;
    private Socket mSocket;
    public Connector(){
    }

    //-单例-----------------------------------------------
    private static Connector instance;
    public static Connector getInstance() {
        if (instance == null) {
            synchronized (Connector.class) {
                if (instance == null) {
                    instance = new Connector();
                }
            }
        }
        return instance;
    }

    //-监听-----------------------------------
    protected ConnectorListener mListener;
    public void setConnectorListener(ConnectorListener listener) {
        this.mListener = listener;
    }
    public interface ConnectorListener {
        void pushData(String data);
    }

    public void connect(){
        try {
            if (mSocket == null || mSocket.isClosed()) {
                mSocket = new Socket(dstName, dstPort);
            }
            //发送数据
            new Thread(new RequestWorker()).start();
            //接受数据
            new Thread(new ReceiveWorker()).start();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //-一般使用这个方法----------------------------------------------------
    public void connect(AuthRequest auth){
        connect();
        putRequest(auth);
    }


    private ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(8);
    private class RequestWorker implements Runnable{
        @Override
        public void run() {
            OutputStream out = null;
            try {
                out = mSocket.getOutputStream();
                while(true){
                    String content = queue.take();
                    out.write(content.getBytes());
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void putRequest(String content){
        try {
            queue.put(content);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void putRequest(Request request) {
        putRequest(request.getData());
    }

    private class ReceiveWorker implements Runnable{
        @Override
        public void run() {
            try {
                InputStream inputStream = mSocket.getInputStream();
                byte[] buffer = new byte[1024];
                int len = -1;
                while((len = inputStream.read(buffer))!=-1){
                    String text = new String(buffer, 0, len);
                    if (mListener !=null) {
                        mListener.pushData(text);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public void disConn(){
        try {
            if (mSocket != null && !mSocket.isClosed()) {
                mSocket.close();
                mSocket = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

三、创建服务,在后台不断的发送广播

public class CoreService extends Service implements ConnectorListener{

    private Connector connector;
    private ExecutorService mPools;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        connector = Connector.getInstance();
        connector.setConnectorListener(this);
        mPools = Executors.newFixedThreadPool(3);
        mPools.execute(new Runnable() {
            @Override
            public void run() {
                AuthRequest request = null;
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
                    request = new AuthRequest("B", "B");
                } else {
                    request = new AuthRequest("A", "A");
                }
                connector.connect(request);
            }
        });
    }

    @Override
    public void pushData(String data) {
        Intent intent = new Intent();
        intent.setAction(PushReceiver.ACTION_TEXT);
        intent.putExtra(PushReceiver.DATA_KEY, data);
        //使用广播的形式把数据发送到主界面进行处理
        sendBroadcast(intent);
    }

}

广播类:

public abstract class PushReceiver extends BroadcastReceiver {
    public static final String ACTION_TEXT = "com.android.action.text";
    public static final String DATA_KEY = "data";
}

四、主界面的实现:

public class MainActivity extends ActionBarActivity {
    private EditText mEtContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEtContent = (EditText) findViewById(R.id.edit_query);
        startService(new Intent(this, CoreService.class));
    }

    public void sendMsg(View view){
        String content = mEtContent.getText().toString();
        if (TextUtils.isEmpty(content)) {
            return;
        }
        String sender = null;
        String token = null;
        String receiver = null;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR2) {
            sender = "B";
            receiver = "A";
            token = "B";
        }else {
            sender = "A";
            token = "A";
            receiver = "B";
        }
        Request request = new TextRequest(sender, token, receiver, content);
        Connector.getInstance().putRequest(request);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mReceiver != null) {
            IntentFilter filter = new IntentFilter(PushReceiver.ACTION_TEXT);
            registerReceiver(mReceiver, filter);
        }
    }

    private PushReceiver mReceiver = new PushReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (PushReceiver.ACTION_TEXT.equals(action)) {
                String result = intent.getStringExtra(PushReceiver.DATA_KEY);
                Toast.makeText(getApplicationContext(), result,
                        Toast.LENGTH_SHORT).show();
            }

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
    }


}

五、服务器类

public class TCPServer {
    private static Map<String, Socket> clients = new LinkedHashMap<String, Socket>();

    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket();
            while(true){
                final Socket client = server.accept();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            InputStream inputStream = client.getInputStream();
                            byte[] buffer = new byte[1024];
                            int len = -1;
                            while((len = inputStream.read(buffer))!= -1){
                                String text = new String(buffer, 0, len);
                                Type tokenType = new TypeToken<Map<String, String>>(){}.getType();
                                Map<String, String> map = new Gson().fromJson(text, tokenType);
                                String type = map.get("type");
                                if ("request".equals(type)) {
                                    String action = map.get("action");
                                    if ("auth".equals(action)) {
                                        String sender = map.get("sender");
                                        String token = map.get("token");
                                        clients.put(sender,client);                                 
                                    }else if ("text".equals(action)) {
                                        // 文本消息
                                        //String sender = map.get("sender");
                                        String receiver = map.get("receiver");
                                        String content = map.get("content");

                                        Socket s = clients.get(receiver);

                                        //依次回复消息
                                        if (s != null) {
                                            OutputStream out = s.getOutputStream();
                                            out.write(content.getBytes());
                                        }
                                    }
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

———————————————————————
(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入门)
——————————————————————–

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

lovoo

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

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

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

打赏作者

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

抵扣说明:

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

余额充值