Android 端 Socket 示例

作者: HarryXR | 来源:发表于2017-02-23 15:59 被阅读117次
    capture.png

    本文基于TCP协议,简单开发了Client,Server端的通信,不废话,直接上代码。

    Client端

    ClientActivity.java

    public class ClientActivity extends Activity {
    
        private static final int MESSAGE_RECEIVE=0x1001;
        @BindView(R.id.edit_content)
        TextView mEdit;
        @BindView(R.id.btn_send)
        TextView mSend;
        @BindView(R.id.tv_content)
        TextView mTvContent;
    
        Socket mClientSocket = null;
        PrintWriter mPrintWriter;
    
        String edit;
        public Handler myHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == MESSAGE_RECEIVE) {
                    //显示接受的服务端信息
                    mTvContent.append(msg.obj + "\n");
                }
            }
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_client);
            ButterKnife.bind(this);
    
            //启动服务端
            Intent intent = new Intent(this, ServerService.class);
            startService(intent);
    
            //发送消息给服务端
            mSend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendMsg();
                }
            });
            // 连接服务器
            new Thread() {
                @Override
                public void run() {
                    connectServer();
                }
            }.start();
        }
    
        private void connectServer() {
            Socket socket = null;
            while (socket == null) {
                try {
                    socket = new Socket("localhost", 3000);
                    mClientSocket = socket;
                    mPrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),
                        true);
                    myHandler.obtainMessage(MESSAGE_RECEIVE, "client:connect server success").sendToTarget();
                } catch (IOException e) {
                    e.printStackTrace();
                    myHandler.obtainMessage(MESSAGE_RECEIVE, "client:connect server fail").sendToTarget();
                }
            }
    
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while (!ClientActivity.this.isFinishing()) {
                    String msg = br.readLine();
                    System.out.println("receive:" + msg);
                    if (msg != null) {
                        String time = formateTime(System.currentTimeMillis());
                        String showMsg = "server " + time + ":" + msg + "\n";
                        myHandler.obtainMessage(MESSAGE_RECEIVE, showMsg).sendToTarget();
                    }
                }
                System.out.print("quit...");
                mPrintWriter.close();
                br.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        private String formateTime(long l) {
            return new SimpleDateFormat("(HH:mm:ss)").format(new Date(l));
        }
    
        private void sendMsg() {
            edit = mEdit.getText().toString();
    
            if (!TextUtils.isEmpty(edit) && mPrintWriter != null) {
                try {
                    new Thread() {
                        @Override
                        public void run() {
                            mPrintWriter.println(edit);
                        }
                    }.start();
    
                    String time = formateTime(System.currentTimeMillis());
                    mTvContent.append("client:" + time + ":" + edit + "\n");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    
        @Override
        protected void onDestroy() {
            if(mClientSocket != null) {
                try {
                    mClientSocket.shutdownInput();
                    mClientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            super.onDestroy();
        }
    }
    

    Server 端

    服务端是在后台启动一个Service,进行无限循环,读取发送消息
    ServerService.java

    public class ServerService extends Service {
     public String[] mDefMessages = {"你好啊", "你发的什么东西啊", "不要再骚扰我了", "哪里跑", "俺老孙来也"};
    
        private boolean mIsServiceDestroyed = false;
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
    
            new Thread(new TcpServiceThread()).start();
    
            return super.onStartCommand(intent, flags, startId);
        }
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        public class TcpServiceThread implements Runnable {
    
            @Override
            public void run() {
    
    
                try {
                    ServerSocket ss = new ServerSocket(3000); ////创建一个ServerSocket对象
                    while (!mIsServiceDestroyed) {
                        final Socket client = ss.accept(); //调用ServerSocket的accept()方法,接受客户端所发送的请求
                        new Thread() {
                            @Override
                            public void run() {
                                try {
                                    responseClient(client);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }.start();
                    }
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
    
        private void responseClient(Socket client) throws IOException {
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    
            //发送消息给客户端
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
            out.println("欢迎来到聊天室");
    
            while (!mIsServiceDestroyed) {
                //读取客户端消息
                String str = in.readLine();
                System.out.println("msg from client:" + str);
                if (str == null) {
                    break;//客户端断开
                }
                int i = new Random().nextInt(mDefMessages.length);
                String msg = mDefMessages[i];
                out.println(msg);
                System.out.println("send msg to client:" + msg);
            }
            System.out.println("client quit...");
            out.close();
            in.close();
            client.close();
        }
    
        @Override
        public void onDestroy() {
            mIsServiceDestroyed = true;
            super.onDestroy();
        }
    

    注意点

    • socket 实例化必须在子线程
    • PrintWriter 发送消息必须在子线程

    本文只是socket的简单实用,不涉及跨进程,后续再考虑。读者有问题、意见,欢迎评论。
    Demo在这里

    相关文章

      网友评论

        本文标题:Android 端 Socket 示例

        本文链接:https://www.haomeiwen.com/subject/jbdbwttx.html