Android send and get socket message with socket

旧时模样 提交于 2021-01-07 06:33:33

问题


I want to send a message with a socket. I checked all my options for receiving and sending messages (if there is a better way than this please tell me). I have a problem. I saw in the video how to do it, but they do not show how to send a message with it. How can I send a message with this? How do I use the "Thread3" class?

    private PrintWriter output;
    private BufferedReader input;
    class Thread1 implements Runnable {
        @Override
        public void run() {
            Socket socket;
             try {
                 socket = new Socket("105.07.60.74", 6791);
                 output = new PrintWriter(socket.getOutputStream());
                 input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                 runOnUiThread(new Runnable() {
                     @Override
                     public void run() {
                         Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT).show();
                     }
                 });

                 new Thread(new Thread2()).start();

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

    class Thread2 implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    final String message = input.readLine();
                    if (message != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "Server: " + message, Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        Thread Thread1 = new Thread(new Thread1());
                        Thread1.start();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    class Thread3 implements Runnable {
        private String message;
        
        Thread3(String message) {
            this.message = message;
        }
        
        @Override
        public void run() {
            output.write(message);
            output.flush();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "Sent", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

来源:https://stackoverflow.com/questions/65236804/android-send-and-get-socket-message-with-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!