Android开发笔记: TcpServer通讯案例

1 这是一个TcpServer封装的类,与Activity之间是通过Handler传递更新数据的

package startapp.cuanbo.startoneapp;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Administrator on 2018/3/30.
 */

class TcpServerThread extends Thread  {

    Handler handler = null;
    private int port;
    Socket client;
    private byte buffer[] = new byte[500];
    InputStream inputStream;
    OutputStream outputStream;

    ServerSocket serverSocket;


    public TcpServerThread(Handler handler,int port){
        this.port = port;
        this.handler = handler;
    }

    @Override
    public void run() {
        super.run();

        try {
            serverSocket = new ServerSocket(port);//监听8080端口,这个程序的通信端口就是8080了

        } catch (IOException e) {
            Log.d("server IOException:", e.getMessage().toString());
        }

        while (true){
            try{
                client = serverSocket.accept();
                inputStream = client.getInputStream();
                outputStream = client.getOutputStream();
                //启动接收线程
                Receive_Thread receive_Thread = new Receive_Thread();
                receive_Thread.start();
            }
            catch (IOException e){
                Log.d("client IOException:", e.getMessage().toString());
            }
        }
    }

    public void sendData(String msg){

        if (outputStream != null &&client != null && client.isConnected()){
            try {
                outputStream.write(msg.getBytes());
            } catch (IOException e) {
                Log.d("sendData IOException:", e.getMessage().toString());
            }
        }
    }

    /**
     *
     * 接收线程
     *
     */
    class Receive_Thread extends Thread//继承Thread
    {
        public void run()//重写run方法
        {
            while (true)
            {
                try
                {
                    final byte[] buf = new byte[1024];
                    final int len = inputStream.read(buf);
                    if (len != -1) {
                        final String text = new String(buf, 0, len);

                        Message msg = new Message();
                        String pageName = "";
                        if (text.contains("StartApp:")) {
                            pageName = text.substring("StartApp:".length(), text.length());
                            msg.what = 0x10;
                            msg.obj = pageName;
                            handler.sendMessage(msg);
                        } else if (text.startsWith("StopApp:")) {
                            pageName = text.substring("StopApp:".length(), text.length());
                            msg.what = 0x11;
                            msg.obj = pageName;
                            handler.sendMessage(msg);
                        }
                        else {
                            msg.what = 0x12;
                            msg.obj = text;
                            handler.sendMessage(msg);
                        }

                    }
                }
                catch (Exception e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

2 调用方法

    在Activity中添加代码,即可

   

 mHandel = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0x10){
                    // 打开一个app
                    startAPP(msg.obj.toString());
                    tcpServerTread.sendData("start app ok\r\n");
                }
                else if (msg.what == 0x11){
                    //关闭一个app
                    stopAPP(msg.obj.toString());
                    tcpServerTread.sendData("stop app ok\r\n");
                }

                Log.d("SOA", msg.obj.toString());

                final String data = msg.obj.toString();
                tv_recv.post(new Runnable() {
                    @Override
                    public void run() {
                        tv_recv.append(data + "\r\n");
                    }
                });
            }
        };
        
        
        TcpServerThread tcpServerTread = new TcpServerThread(mHandel,9090);
        tcpServerTread.start();
        













你可能感兴趣的:(Android开发笔记)