2

几天前,我尝试创建一个服务器 - 客户端或客户端服务器作为实验来学习使用线程的套接字,但后来有人告诉我应该使用 swingWorker。我做了一些研究如何使用并在实践中实施它,但它仍然不起作用。即使我获得了连接并使用了.excute(),swingWorker 线程看起来也没有运行。如果你们能帮助找出我做错的地方,那就太好了。SwingWorker 类在 startSever() 和 startClient() 方法中。

    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();
}
4

3 回答 3

6

这是一个非常基本的例子。

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

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

客户

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

服务器

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

更新(呜呜)

虽然我面前有你的源代码......

应该非常、非常、很少需要做textMessage.addKeyListener(this)

因为您使用的是 a JTextField,所以您应该使用 a ActionListener。这有很多重要的原因,但对您来说,主要原因是“接受”操作依赖于外观和感觉这一事实。虽然大多数系统确实使用Enter了“接受”动作,但并不能保证。

查看如何编写动作侦听器以获取更多信息

鉴于您尝试做的事情的一般复杂性,+1 表示整体良好的尝试!

于 2013-01-31T02:47:46.300 回答
5

使用此示例,以下更改适用于单个 telnet 客户端。

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;
}
于 2013-01-31T02:49:00.877 回答
-1

我看到你的服务器端口是 8900,你的客户端端口也是 8900。我不确定服务器和客户端是否在同一台机器上运行是否重要......

于 2013-01-31T02:36:53.353 回答