1

编辑:我解决了我的问题:

while(!finish.equals("readline")){
    publish(finish);
    finish = Main.in.readLine();
}

必须改为:

while(true){
    publish(finish);
    finish = Main.in.readLine();
}

老问题:

我正在用 Java 编写一个聊天应用程序,我制作了一个简单的 Gui,它运行良好。但现在我已经重写了收集聊天消息的部分,使其成为线程安全的。登录时,服务器将聊天中的所有消息推送到客户端,这很好用。在那一刻之后,GUI继续响应,我可以发送命令并且它们到达服务器但是没有调用过程方法,所以没有返回任何内容。我究竟做错了什么?

这是我正在谈论的代码:

package Client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;

import javax.swing.SwingWorker;

public class ChatReceiver extends SwingWorker<Void, String> {
    @Override
    protected Void doInBackground() {
        try {
            Main.echoSocket = new Socket(Main.ip, 4444);
            Main.out = new PrintWriter(Main.echoSocket.getOutputStream(), true);
            Main.in = new BufferedReader(new InputStreamReader(
                    Main.echoSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host.");
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for "
                    + "the connection to: localhost.");
        }
        publish("Sending Login-Request...");
        Main.out.println("login");
        try {
            String text = Main.in.readLine();
            String status = Main.in.readLine();
            publish("Receiving: " + text + " " + status);
            if(status.equals("readline") && text.equals("ready")){
                String finish = "logging in...";
                Main.out.println(Main.name + " SZUTKEY");
                while(!finish.equals("readline")){
                    publish(finish);
                    finish = Main.in.readLine();
                }
            }else{
                throw new RuntimeException("Fuck it login died!");
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void process(List<String> chats) {
        Main.printTest("xxx");
        for(String s : chats.toArray(new String[0])){
            Main.printTest("called");
            Main.printTest(s);
        }
        Main.textField.validate();
        Main.textField.repaint();
    }
}

这在我的 Gui 中被调用:

    loginAction  = new AbstractAction("Login") {

        /**
         * 
         */
        private static final long serialVersionUID = -3279591081543889275L;

        @Override
        public void actionPerformed( ActionEvent arg0 ) {
            name = JOptionPane.showInputDialog("Please input your Chatname");
            ip = JOptionPane.showInputDialog("Please input the Chatserver-IP", "localhost");
            (chat = new ChatReceiver()).execute();
        }
    };
4

1 回答 1

2
于 2012-11-21T07:22:30.003 回答