JavaFX while(true)循环冻结应用程序

时间:2015-03-30 13:30:53

标签: javafx-8

我有一个问题,我整晚都在打我的脑袋。这个应用程序作为Java.swing应用程序工作正常但不幸的是,对于JavaFX和Java8的转换,事情有点棘手。对话框当然没有很好的翻译,但我得到了解决。我正在击打我的头部是在while(真)循环。它循环接收来自服务器的SUBMIT和ACCEPT消息,但之后冻结。我试过System.out.println();整个程序的服务器和客户端,并已将问题追溯到该单点。有任何想法吗?我最初没有线程,但有同样的问题。我将while(true)循环改为while(i< 1)将MESSAGE else if语句移入它自己的while(true)if语句中,因为它是我需要循环多次的唯一线程。

客户端文件

package application;

import java.awt.TextArea;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.SocketException;
    import java.net.SocketTimeoutException;
    import java.net.UnknownHostException;

    import javafx.application.Application;
    import javafx.fxml.FXML;
    import javafx.stage.Stage;

    public class Client implements Runnable {


        @FXML
        public static
        TextArea InputTA;
        @FXML
        public static
        TextArea MainTA;
        public static BufferedReader clientIn;
        public static PrintWriter clientOut;
        int i = 1;
        static String readLine;


        @FXML
        public void run(){
            /* 
             * @ALambert
             * 
             * Here we initialize the socket, connect to the server we desire and setup
             * our BufferedReader and PrintWriter
             * 
             */

            final int PORT = 8000;      
            String serverAddress = ServerIPPopup.serverIP;
            try {

                Socket socket = new Socket(serverAddress, PORT);
                System.out.println("Server Connected");
                clientIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                System.out.println("Buffered Reader Set");
                clientOut = new PrintWriter(socket.getOutputStream(), true);
                System.out.println("Print Writer Set");
                /* 
                 * @Andrew Lambert
                 * 
                 * In this section we set our Screen Name as well 
                 * as start relaying messages to the server
                 * 
                 */



                 while (true) {
                        String readLine = clientIn.readLine();                      
                        System.out.println("readLine Set");

                         if (readLine.startsWith("NAME")) {     
                             ThreadClass.submittedThread st = new ThreadClass.submittedThread();
                             st.start();
                         }else if (readLine.startsWith("ACCEPTED")) {
                                 ThreadClass.acceptedThread at = new ThreadClass.acceptedThread();
                                 at.start();
                                 continue;
                           }else if (readLine.startsWith("MESSAGE")){
                               ThreadClass.messageThread mt = new ThreadClass.messageThread();
                               mt.start();
                           }
                            }



            } catch (UnknownHostException e) {
                System.out.println("UnknownHostException");
                //e.printStackTrace();
            }catch(SocketTimeoutException s){
                System.out.println("SocketTimeoutException");
                //s.printStackTrace();
            } catch (SocketException e) {
                System.out.println("SocketException");
                // TODO Auto-generated catch block
                //e.printStackTrace();
        //  } catch (InterruptedException e) {
        //      System.out.println("InterruptedException");
                // TODO Auto-generated catch block
                //e.printStackTrace();
            } catch (IOException e) {
                System.out.println("IOException");
                // TODO Auto-generated catch block
                //e.printStackTrace();
            } 

            /* 
             * @ALambert
             * 
             * 
             */         
        }


        }

服务器文件

package application;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;


public class Server {

    public static final int PORT = 8000;


    public static HashSet<String> clientNames = new HashSet<String>();


    public static HashSet<PrintWriter> writers = new HashSet<PrintWriter>();


    public static void main(String[] args) throws Exception {
        System.out.println("The chat server is running.");
        ServerSocket listener = new ServerSocket(PORT);
        try {
            while (true) {
                new Handler(listener.accept()).start();
                System.out.println("The chat server recieved a geust");
            }
        } finally {
            listener.close();
            System.out.println("The chat server closed");
        }
    }


    public static class Handler extends Thread {
        public String clientName;
        public Socket socket;
        public BufferedReader serverIn;
        public PrintWriter serverOut;


        public Handler(Socket socket) {
            this.socket = socket;
        }


        public void run() {
            try {


                serverIn = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
                System.out.println("Buffered Reader Set");
                serverOut = new PrintWriter(socket.getOutputStream(), true);
                System.out.println("Print Writer Set");


                while (true) {                  
                    serverOut.println("NAME");
                    clientName = serverIn.readLine();
                    if (clientName == null) {
                        return;
                    }
                    synchronized (clientNames) {
                        if (!clientNames.contains(clientName)) {
                            clientNames.add(clientName);
                            System.out.println(clientName + " was added to the list");
                            break;
                        }
                    }
                }

                serverOut.println("ACCEPTED");
                writers.add(serverOut);
                System.out.println("Name: " + clientName + " was Accepted");

                while (true) {
                    String clientInput = serverIn.readLine();
                    if (clientInput == null) {
                        return;
                    }
                    for (PrintWriter writer : writers) {
                        System.out.println("message " + clientInput + " recieved from " + clientName);
                        writer.println("MESSAGE " + clientName + ": " + clientInput);
                        System.out.println("message " + clientInput + " sent to " + clientName);
                    }
                }
            } catch (IOException e) {
                System.out.println(e);
            } finally {

                if (clientName != null) {
                    clientNames.remove(clientName);
                }
                if (serverOut != null) {
                    writers.remove(serverOut);
                }
                try {
                    socket.close();
                } catch (IOException e) {
                }
            }
        }
    }
}

ThreadClass文件

package application;

public class ThreadClass {
    public static class submittedThread extends Thread{
        submittedThread(){      
            Client.clientOut.println(ScreenNamePopup.getName);
            System.out.println("Name: " + ScreenNamePopup.getName + " Submitted");              
    }
    }    
    public static class acceptedThread extends Thread{
        acceptedThread(){
            System.out.println("Name: " + ScreenNamePopup.getName + " Accepted");                               
    }
    } 
    public static class messageThread extends Thread{
        messageThread(){

            System.out.println("Message recieved from Server");                                 
    }
    }
}

static void Main

package application;

import java.io.IOException;
import java.util.Optional;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Dialogs;
import javafx.scene.control.TextInputDialog;
import javafx.stage.Stage;

/*
 * 
 * 
 * 
 * 
 * 
 */
public class Main extends Application {


    @Override
    public void start(Stage stage) throws Exception {
        try{
        Parent root = FXMLLoader.load(getClass().getResource("IRCFXML.fxml"));

        stage.setTitle("CO-OP IRC Project");
        stage.setScene(new Scene(root, 450, 450));
        stage.show();


    } catch (IOException e) {
        System.err.println("Error loading IRCFXML.fxml!");
        e.printStackTrace();
        System.exit(0);
    }
    }




    public static void main(String[] args) throws IOException{
        launch(args);

    }
}

IRCController

package application;

import java.io.IOException;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextInputDialog;

import java.util.Optional;

import javafx.application.Application;
import javafx.stage.Stage;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;

import javafx.fxml.LoadException;

public class IRCController{
    @FXML
    public
    TextArea MainTA;
    @FXML
    public
    TextArea InputTA;
    @FXML
    public
    Button reset;
    @FXML
    public
    Button handlerbutton;
    @FXML
    public
    Button submit;
    @FXML
    public
    Button serverButton;
    @FXML
    public
    Button screenNameButton;


    @FXML
    private void initialize() throws Exception{

        InputTA.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable,
                    String oldValue, String newValue) {


            }
        });

        MainTA.textProperty().addListener(new ChangeListener<String>() {
                @Override
                public void changed(ObservableValue<? extends String> observable,
                        String oldValue, String newValue) {


                }


            });     
    }

    @FXML 
    public void handleSubmitButtonAction(){
        String clientOutString = InputTA.getText();
        Client.clientOut.println(clientOutString);
        InputTA.setText("");

    }
    @FXML 
    public void handleServerButton(){
        ServerIPPopup sipp = new ServerIPPopup();
        sipp.run();


    }
    @FXML 
    public void handleScreenNameButton(){
        ScreenNamePopup scpp = new ScreenNamePopup();
        scpp.run();
    }

}

ServerIP Popup

package application;

import java.util.Optional;

import javafx.application.Application;
import javafx.scene.control.TextInputDialog;
import javafx.stage.Stage;

public class ServerIPPopup implements Runnable{
    public static String serverIP;

    public void run(){
        /*
         * @ALambert
         * 
         * dialog popup to gather the ip address of the server you wish to connect to.
         * 
         * 
         */


            TextInputDialog dialog = new TextInputDialog("localhost");
            dialog.setTitle("Server IP");
            dialog.setHeaderText("Server IP");
            dialog.setContentText("Please enter the Server IP");
            Optional<String> result = dialog.showAndWait();
            if (result.isPresent()){
                System.out.println("Client Side-Server IP " + result.get());
                serverIP = result.get();
                ScreenNamePopup scp = new ScreenNamePopup();
                scp.run();
            }

    }



}

ScreenName Popup

package application;

import java.util.Optional;

import javafx.application.Application;
import javafx.scene.control.TextInputDialog;
import javafx.stage.Stage;

public class ScreenNamePopup  implements Runnable{
    public static String getName;
    public void run(){

                /*
                 * @ALambert
                 * 
                 * popup dialog box to gather the screen name you wish to use for the chat session
                 * 
                 */             
                TextInputDialog dialogScreenName = new TextInputDialog("Screen Name");
                dialogScreenName.setTitle("Screen Name");
                dialogScreenName.setHeaderText("Screen Name");
                dialogScreenName.setContentText("Choose a screen name:");
                Optional<String> resultScreenName = dialogScreenName.showAndWait();
                if (resultScreenName.isPresent()){
                    System.out.println("Client Side-Screen Name: " + resultScreenName.get());
                    getName = resultScreenName.get();
                    Client client = new Client();
                    client.run();
                }
            }





}

我当然还有很多工作要做。我一步一步迈出这一步,在这个问题得到解决之后,希望我能开始研究下一个难题(即合并MainTA.append(&#34;等等等等等等);各方面,所以我可以让人们说话。任何建议将不胜感激。

编辑: 经过一些批评,我继续前进,清理了我的代码中的一些问题。有些错误是盲目尝试偶然发现早期问题,即使对话框正常工作或让BufferedReader和PrintWriters工作。其他人是因为我从来不知道,但现在这样做。我研究了线程阻塞,并找到了一个用socket来停止冻结的方法.soTimeOut();但尚未找到让它到达街区的MESSAGE部分的方法。我已经尝试将它们分成单独的线程,将while(true)更改为一段时间(readLine!= null),注释掉服务器和客户端的NAME和ACCEPT部分,但出于某种原因,我采用了什么途径为了让它读取块的MESSAGE部分,它似乎冻结了程序。我将更多地研究服务器的同步部分,看看代码的这一部分是否可能导致客户端出现某种问题。我并不认为是这样,但我不知所措。

0 个答案:

没有答案