Java socket swingWorker running but no message received or transmitted

前端 未结 3 510
无人及你
无人及你 2020-11-29 13:06

A few days ago i tried to create a server - client or client Server as an experiment to learn about socket using a thread but then someone told me that i should use swingWor

相关标签:
3条回答
  • 2020-11-29 13:29

    Using this example, the following changes work with a single telnet client.

    private PrintWriter out;
    ...
    public void keyPressed(KeyEvent e) {
        if (e.getKeyChar() == KeyEvent.VK_ENTER) {
            myMessage = friendLabel + textMessage.getText();
        if (out != null) {
            out.println(myMessage);
        }
        ...
    }
    ...
    protected Void doInBackground() {
        try {
            listeningSocket = new ServerSocket(port);
            System.out.println("Waiting for connection");
            connection = listeningSocket.accept();
            connected = true;
            System.out.println("Connected");
            Scanner in = new Scanner(connection.getInputStream());
            out = new PrintWriter(connection.getOutputStream(), true);
            publish("Connected");
            while (true) {
                publish(in.nextLine());
            }
        } catch (IOException e) {
            clientMessage = "Connection Lost";
            try {
                connection.close();
                System.out.println("Closed");
            } catch (IOException e1) {
                e1.printStackTrace();
                connected = false;
            }
        }
        return null;
    }
    
    0 讨论(0)
  • 2020-11-29 13:38

    Here's a VERY basic example.

    Basically, because you program requires asynchronous communications (that is, you need to be able to read from the socket AND write to it at the same time), you need to offload each stream to a separate thread.

    The management process of this example is, well, no existent. Realistically, you should have some kind of "connection" manager that would be able to cleanly close the output and input threads so that, for example, when the user types "bye", the output thread would be able to tell the connection manager that the connection should be terminated. It would then tell the input thread to stop reading any new message and terminate...

    Client

    public class Client {
    
        public static void main(String[] args) {
    
            try {
                Socket master = new Socket("localhost", 8900);
                new Thread(new InputHandler(master)).start();
                new Thread(new OuputHandler(master)).start();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
    
        }
    
        public static class InputHandler implements Runnable {
    
            private Socket socket;
    
            public InputHandler(Socket socket) {
                this.socket = socket;
            }
    
            @Override
            public void run() {
                boolean commune = true;
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    while (commune) {
                        String text = reader.readLine();
                        System.out.println("\n<server> " + text);
                        if (text.toLowerCase().equals("bye")) {
                            commune = false;
                        }
                    }
                } catch (Exception exp) {
                    exp.printStackTrace();
                } finally {
                    try {
                        reader.close();
                    } catch (Exception e) {
                    }
                    try {
                        socket.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
    
        public static class OuputHandler implements Runnable {
    
            private Socket socket;
    
            public OuputHandler(Socket socket) {
                this.socket = socket;
            }
    
            @Override
            public void run() {
                boolean commune = true;
                BufferedWriter writer = null;
                try {
                    writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    Scanner scanner = new Scanner(System.in);
                    while (commune) {
                        System.out.print("> ");
                        String text = scanner.nextLine();
                        writer.write(text);
                        writer.newLine();
                        writer.flush();
                        if (text.equalsIgnoreCase("bye")) {
                            commune = false;
                        }
                    }
                } catch (Exception exp) {
                    exp.printStackTrace();
                } finally {
                    try {
                        writer.close();
                    } catch (Exception e) {
                    }
                    try {
                        socket.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
    }
    

    Server

    public class Server {
    
        public static void main(String[] args) {
    
            try {
                ServerSocket master = new ServerSocket(8900);
                Socket socket = master.accept();
                new Thread(new InputHandler(socket)).start();
                new Thread(new OuputHandler(socket)).start();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
    
        }
    
        public static class InputHandler implements Runnable {
    
            private Socket socket;
    
            public InputHandler(Socket socket) {
                this.socket = socket;
            }
    
            @Override
            public void run() {
                boolean commune = true;
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    while (commune) {
                        String text = reader.readLine();
                        System.out.println("\n<client> " + text);
                        if (text.toLowerCase().equals("bye")) {
                            commune = false;
                        }
                    }
                } catch (Exception exp) {
                    exp.printStackTrace();
                } finally {
                    try {
                        reader.close();
                    } catch (Exception e) {
                    }
                    try {
                        socket.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
        public static class OuputHandler implements Runnable {
    
            private Socket socket;
    
            public OuputHandler(Socket socket) {
                this.socket = socket;
            }
    
            @Override
            public void run() {
                boolean commune = true;
                BufferedWriter writer = null;
                try {
                    writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    Scanner scanner = new Scanner(System.in);
                    while (commune) {
                        System.out.print("> ");
                        String text = scanner.next();
                        writer.write(text);
                        writer.newLine();
                        writer.flush();
                        if (text.equalsIgnoreCase("bye")) {
                            commune = false;
                        }
                    }
                } catch (Exception exp) {
                    exp.printStackTrace();
                } finally {
                    try {
                        writer.close();
                    } catch (Exception e) {
                    }
                    try {
                        socket.close();
                    } catch (Exception e) {
                    }
                }
            }
        }
    }
    

    Update (whine)

    While I have your source code in front of me...

    There should very, very, rarely be a need to do textMessage.addKeyListener(this)

    Because you are using a JTextField, you should be using a ActionListener instead. There are a a number of important reasons for this, but for you, the main one would be the fact that a "accept" action is Look and Feel dependent. While most systems do use Enter as there "accept" action, is not a guarantee.

    Have a look at How to Write a Action Listener for more information

    Given the general complexity of what you are trying to do, +1 for a overall good attempt!

    0 讨论(0)
  • 2020-11-29 13:38

    I see your server port is 8900 and your client port is 8900 too. I am not sure if it matters if the server and client are running on the same machine...

    0 讨论(0)
提交回复
热议问题