当前位置: 首页 > 工具软件 > chat-app > 使用案例 >

ChatAPP------开发(基本原理)

方俊
2023-12-01

一,简介基本原理:启动ChatAPP时,同时启动ServerSocket,不断循环接收,相当于一个简易的服务器。用于接收别的客户端发过来的信息,于此同时布局客户端,使其能够发送信息到别的ChatAPP。



二,实现
1,ServerSocket的创建和实现

private ServerSocket serverSocket = null;

   /*
    服务器端接收数据
    需要注意以下一点:
    服务器端应该是多线程的,因为一个服务器可能会有多个客户端连接在服务器上;
    */
    private void receiveData() {
        Thread thread = new Thread(){
            @Override
            public void run() {
                super.run();
                /*
                指明端口号
                 */
                try {
                    serverSocket = new ServerSocket(8000);
                }catch (IOException e){
                    e.printStackTrace();
                }
                GetIpAddress.getLocalIpAddress(serverSocket);

                Message message_1 = handler.obtainMessage();
                message_1.what = 1;
                message_1.obj = "IP:" + GetIpAddress.getIP() + " PORT: " + GetIpAddress.getPort();
                handler.sendMessage(message_1);
                /*
                循环启动服务
                 */
                boolean b = true;
                while (b){
                    Socket socket = null;
                    try {
                        if (!serverSocket.isClosed()){
                            socket = serverSocket.accept();
                            inputStream = socket.getInputStream();
                            new ServerThread(socket,inputStream).start();
                        }else {
                            b = false;
                            socket.close();
                            return;
                        }

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

                }

            }
        };
        thread.start();
}

class ServerThread extends Thread{

        private Socket socket;
        private InputStream   inputStream;
        private StringBuffer stringBuffer = MainActivity.this.stringBuffer;


        public ServerThread(Socket socket,InputStream inputStream){
            this.socket = socket;
            this.inputStream = inputStream;
        }

        @Override
        public void run() {
            int len;
            byte[] bytes = new byte[20];
            boolean isString = false;

            try {
                //在这里需要明白一下什么时候其会等于 -1,其在输入流关闭时才会等于 -1,
                //并不是数据读完了,再去读才会等于-1,数据读完了,最结果也就是读不到数据为0而已;
                while ((len = inputStream.read(bytes)) != -1) {
                    for(int i=0; i<len; i++){
                        if(bytes[i] != '\0'){
                            stringBuffer.append((char)bytes[i]);
                        }else {
                            isString = true;
                            break;
                        }
                    }
                    if(isString){
                        Message message_2 = handler.obtainMessage();
                        message_2.what = 2;
                        message_2.obj = stringBuffer;
                        handler.sendMessage(message_2);
                        isString = false;
                    }

                }
                //当这个异常发生时,说明客户端那边的连接已经断开
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    inputStream.close();
                    socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

            }

        }
    }

2,本机IP地址的获取

/**
* 获取IP地址和端口号
*/
public class GetIpAddress {

    public static String IP;
    public static int PORT;

    public static String getIP(){
        return IP;
    }
    public static int getPort(){
        return PORT;
    }
    public static void getLocalIpAddress(ServerSocket serverSocket) {

        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    String mIP = inetAddress.getHostAddress().substring(0, 3);
                    if (mIP.equals("192")) {
                        IP = inetAddress.getHostAddress();    //获取本地IP
                        PORT = serverSocket.getLocalPort();    //获取本地的PORT
                        Log.e("IP", "" + IP);
                        Log.e("PORT", "" + PORT);
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
}


 

 类似资料: