Android TCP通信(二)

在Android TCP通信(一)中我们自己写了一个简易的服务器,以及在android 客户端程序发送消息给那个服务器。

如果客户端发送的消息需要异步响应,又该怎么处理呢?

这里我参考了 别人的代码,做了一个改进。

服务端

package com.cmcc.iot;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SocketServerThreadPool {
    private static final int PORT = 12345;
    private List<Socket> mList = new ArrayList<Socket>();
    private ServerSocket server = null;
    private ExecutorService mExecutorService = null; // thread pool

    public static void main(String[] args) {
        new SocketServerThreadPool();
    }

    public SocketServerThreadPool() {
        try {
            server = new ServerSocket(PORT);
            mExecutorService = Executors.newCachedThreadPool(); // create a
                                                                // thread pool
            System.out.println("服务器已启动...");
            Socket client = null;
            while (true) {
                client = server.accept();
                // 把客户端放入客户端集合中
                mList.add(client);
                mExecutorService.execute(new Service(client)); // start a new
                                                                // thread to
                                                                // handle the
                                                                // connection
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class Service implements Runnable {
        private Socket socket;
        private BufferedReader in = null;
        private String msg = "";

        public Service(Socket socket) {
            this.socket = socket;
            try {
                in = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
                // 客户端只要一连到服务器,便向客户端发送下面的信息。
                msg = "服务器地址:" + this.socket.getInetAddress() + "come toal:"
                        + mList.size() + "(服务器发送)";
                this.sendmsg();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        /**
         * 循环遍历客户端集合,给每个客户端都发送信息。
         */
        public void sendmsg() {
            System.out.println(msg);
            int num = mList.size();
            for (int index = 0; index < num; index++) {
                Socket mSocket = mList.get(index);
                PrintWriter pout = null;
                try {
                    pout = new PrintWriter(new BufferedWriter(
                            new OutputStreamWriter(mSocket.getOutputStream())),
                            true);
                    pout.println(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        public void run() {
            try {
                while(true ) {
                    if((msg = in .readLine())!= null) {
                        //当客户端发送的信息为:exit时,关闭连接
                        if(msg .equals("exit" )) {
                            System.out.println("ssssssss" );
                            mList.remove( socket);
                            in.close();
                            msg = "user:" + socket.getInetAddress()
                                + "exit total:" + mList.size();
                            socket.close();
                            this.sendmsg();
                            break;
                            //接收客户端发过来的信息 msg,然后发送给客户端。
                        } else {
                            msg = socket.getInetAddress() + ":" + msg +"(服务器发送)" ;
                            this.sendmsg();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
    }
}

客户端

package com.lq.mypractice.activity;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.lq.mypractice.R;
import com.lq.mypractice.util.LogFactory;
import com.lq.mypractice.util.LogUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketDemoActivity extends Activity {
    private TextView tv_msg = null;
    private EditText ed_msg = null;
    private Button btn_send = null;
    // private Button btn_login = null;
    private static final String HOST = "192.168.205.46";
    private static final int PORT = 12345;
    private Socket socket = null;
    private BufferedReader in = null;
    private PrintWriter out = null;
    private String content = "";
    //接收线程发送过来信息,并用TextView显示
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            tv_msg.setText(content);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket_asyn);

        tv_msg = (TextView) findViewById(R.id.textview);
        ed_msg = (EditText) findViewById(R.id.edittext01);
        btn_send = (Button) findViewById(R.id.button02);

        //发送任务
        new SoketTask().execute();

        btn_send.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String msg = ed_msg.getText().toString();
                if (socket.isConnected()) {
                    if (!socket.isOutputShutdown()) {
                        out.println(msg);
                    }
                }
            }
        });


        //接收任务
        new ReceiveTask().execute();
    }

    private class ReceiveTask extends AsyncTask<Void, Integer, Integer> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Integer doInBackground(Void... params) {
            //启动线程,接收服务器发送过来的数据
            try {
                while (true) {
                    if (!socket.isClosed()) {
                        if (socket.isConnected()) {
                            if (!socket.isInputShutdown()) {
                                if ((content = in.readLine()) != null) {
                                    LogFactory.i("lengqi", content);
                                    content += "\n";
                                    mHandler.sendMessage(mHandler.obtainMessage());
                                } else {

                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }


    }

    private class SoketTask extends AsyncTask<Void, Integer, Integer> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Integer doInBackground(Void... params) {
            try {
                socket = new Socket(HOST, PORT);
                in = new BufferedReader(new InputStreamReader(socket
                        .getInputStream()));
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                        socket.getOutputStream())), true);
            } catch (IOException ex) {
                ex.printStackTrace();
                LogUtils.i("login exception" + ex.getMessage());
            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }
    }


}

注意客户端发送和接收都要写到异步任务里面,不能放到主线程里面操作。

针对有异步响应的,可以写一个监听,回调结果。

参考

http://www.cnblogs.com/devinzhang/archive/2012/10/04/2711763.html

阅读更多
上一篇Markdown 新手指南
下一篇Git 学习(一)
想对作者说点什么? 我来说一句

AndroidTCP通讯实现

2017年04月17日 68KB 下载

TCP、UDP 通信程序设计实验报告

2013年05月05日 91KB 下载

Android实现tcp通讯socket的程序

2017年03月29日 60KB 下载

没有更多推荐了,返回首页

关闭
关闭