Java套接字swingWorker运行但没有收到或传输消息 [英] Java socket swingWorker running but no message received or transmitted

查看:126
本文介绍了Java套接字swingWorker运行但没有收到或传输消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天前,我试图创建一个服务器 - 客户端或客户端服务器作为实验,了解套接字使用线程,但有人告诉我,我应该使用swingWorker。我做了一些研究如何使用和已经实施它作为实践,但它仍然不工作。 swingWorker线程看起来不像它运行,即使我得到一个连接,并已使用.excute()。如果你们可以帮助找到我做错了,那将是巨大的。 SwingWorker类在startSever()和startClient()方法中。

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 swingWorker. I did some research how to use and have implemented it in as practice but it still doesn't work. the swingWorker thread doesn't look like it is running even tho i get a connection and have used .excute(). If you guys can help spot where i am doing wrong that will be great. SwingWorker class is in the startSever() and startClient() method.

    private void startServer() {
        SwingWorker <Void, String> runningServer = new SwingWorker<Void, String>(){
        protected Void doInBackground() {
            try {
                listeningSocket = new ServerSocket(port);
                System.out.println("waiting for connection");
                connection = listeningSocket.accept();
                connected = true;
                System.out.println("Connected");
                String incomeMessage =null;
                while(connected){
                inStream = connection.getInputStream();
                    inDataStream = new DataInputStream(inStream);
                    if (myMessage !=null){
                        outStream = connection.getOutputStream();
                        outDataStream = new DataOutputStream(outStream);
                    outDataStream.writeUTF(myMessage);
                    }

                    if((incomeMessage = inDataStream.readUTF())!=null){
                        clientMessage = incomeMessage;
                        publish(clientMessage);
                        incomeMessage =null;
                    }
                }
            } catch (IOException e) {
                clientMessage = "Connection Lost";
            }
        return null;
    }           
runningServer.execute();
}


推荐答案

基本上,因为你的程序需要异步通信(也就是说,你需要能够从套接字读取并且同时写入),你需要将每个流卸载到单独的线程。

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.

这个例子的管理过程是没有存在的。实际上,你应该有某种连接管理器,能够干净地关闭输出和输入线程,以便例如当用户键入bye时,输出线程将能够告诉连接管理器连接应该终止。然后它会告诉输入线程停止读取任何新消息并终止...

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...

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) {
                }
            }
        }
    }
}

更新(whine)

Update (whine)

我...

很少,很少需要做 textMessage.addKeyListener(this)

因为您使用的是 JTextField ,所以您应该使用 ActionListener 。这有一些重要的原因,但对你来说,主要的一个事实是,接受行动是看和感觉依赖。虽然大多数系统确实使用输入作为接受操作,但不是保证。

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.

查看如何编写动作监听器了解更多信息

考虑到你想要做的事情的一般复杂性,+1为一个整体好的尝试!

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

这篇关于Java套接字swingWorker运行但没有收到或传输消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆