Java值未正确传递给服务器

时间:2018-02-24 19:03:40

标签: java eclipse email javafx

你好我有一个我在Java程序中无法识别的问题。 我有一个本地服务器和一个客户端类,我想将输入的值传递给服务器,服务器验证它 但是当我输入用于将值发送到服务器的按钮时,应用程序崩溃了 非常感谢您的帮助。

以下是我的代码:

这是Client.Java

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.scene.control.*;
import java.io.IOException;
import java.net.*;
import java.io.PrintWriter;
import java.util.Scanner;

public class Client extends Application // for GUI
{
private PrintWriter outputToServer; // send message to server
private Scanner inputFromServer;    // gets response back from the server
//private String username;
private Socket socket;
private static InetAddress host = null;
final int PORT = 1234;

public static void main(String[] args) {
    try {
        host = InetAddress.getLocalHost();
    } catch (UnknownHostException ex) {
        System.out.println("Host ID Not Found");
    }

    do {
        launch(args);
    } while (true);

}


public void start(Stage stage) throws Exception {
    // set up variables

    socket = new Socket(host, PORT);
    // scanner set up so that it can scan for any input stream (responses) that come from the server
    inputFromServer = new Scanner(socket.getInputStream());
    outputToServer = new PrintWriter(socket.getOutputStream(), true);


    Parent root = FXMLLoader.load(getClass().getResource("welcome.fxml"));
    Scene scene;
    scene = new Scene(root, 500, 500);
    //add the scene to the stage
    stage = new Stage();
    stage.setScene(scene);
    stage.show();

}

@FXML
private TextField Input;

@FXML
private void loginButton (ActionEvent event)
{

    String t = Input.getText();
    //validateUsername(t);
    System.out.println(t);
    validateUsername(t);
}


@FXML
private void validateUsername(String username) {
    if (username.isEmpty()) {
       // message.setText("Please enter your username");
    } else {
       //  send username across to the server
    System.out.println(username);

        outputToServer.println(username);
        String serverRequest = inputFromServer.nextLine();

        if (serverRequest.equals("true")) {
            LoadClient();
        }
    }
}

private void LoadClient()
{
    Scene scene;
    VBox vbox;
    Stage stage;

    Button inbox = new Button("Inbox");
    Button email = new Button("Email");
    Button quit = new Button("Quit");

    inbox.setOnAction(e -> getInbox());
    email.setOnAction(e -> getEmail());
    quit.setOnAction(e -> quitApp());

    // add buttons to layout
    vbox = new VBox();
    vbox.getChildren().add(inbox);
    vbox.getChildren().add(email);
    vbox.getChildren().add(quit);

    scene = new Scene(vbox, 500, 500);
    stage = new Stage();
    stage.setScene(scene);
    stage.show();
}

public void getInbox() {
    System.out.println("BEFORE SENDING INBOX REQUEST");
    outputToServer.println("get_inbox");
    System.out.println("AFTER SENDING INBOX REQUEST");
}

public void getEmail() {
    outputToServer.println("send_email");
}

public void quitApp() {
    outputToServer.println("close");
}

}

这是Server.java

import javafx.fxml.FXML;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.net.*;
import java.io.*;
import java.util.Scanner;

public class Server implements Serializable // used to send object from     client to server
{
// list of users of type string
private static ArrayList<String> users = new ArrayList<String>();
private static ArrayList<Email> mails = new ArrayList<Email>();

public static void main(String[] args) throws IOException
{
    // set up 3 users
    users.add("U1");
    users.add("U2");
    users.add("U3");

    Socket client; // client
    ServerSocket serverSocket = null; // server
    final int PORT = 1234;

    ClientHandler clientHandler;

    // set up the server socket
    try
    {
        serverSocket = new ServerSocket(1234);
    }
    catch (IOException ioEx)
    {
        System.out.println("Can't set up port");
        System.exit(1);
    }

    System.out.println("\n Server running");

    do {
        client = serverSocket.accept(); // accept the client to the   server
        // create a function that will validate the user
        String validUser = validateUser(client);
        clientHandler = new ClientHandler(validUser, client);
        clientHandler.start(); // calls the run function

    } while (true);


}

private static String validateUser(Socket client)
{
    Scanner inputFromClient = null;
    PrintWriter outputToClient = null;
    boolean validUser = false;

    try
    {
        // allows the server to retrieve the input from the client
        inputFromClient = new Scanner(client.getInputStream());
        // allow server to send things to the client
        outputToClient = new PrintWriter(client.getOutputStream(),  true);

    }
    catch(IOException io)
    {
        System.out.println("Problem initialising variables");
    }

    // get the input from the client
    String userToValidate = inputFromClient.nextLine();

    while  (validUser == false)
    {
        for(String username : users)
        {
            // check the user to validate matches the user from the  client
            if (username.equals(userToValidate))
            {
                // tell the client that user is valid
                validUser = true;
                break;
            }
    }

        if(validUser == false)
        {
            // user is invalid so wait for a new user to pass from the client to the server
            outputToClient.println("false");
            userToValidate = inputFromClient.nextLine();
        }
        else
        {
            outputToClient.println("true");
        }

    }
    // return the correct username
    return userToValidate;

}


// get the mail from the server so it can be accessed in the clienthandler
private static ArrayList<Email> getMail()
{
    return mails;
}

}
// each client will have their unique username
class ClientHandler extends Thread implements Serializable
{
private Socket client;
// retrieve requests from the client
private Scanner input;
// send requests to the client
private PrintWriter output;
private String username;

public ClientHandler(String username, Socket client)
{
    this.username = username;
    this.client = client;
    System.out.println("BEFORE TRY");
    try
    {
        input = new Scanner(client.getInputStream());
        output = new PrintWriter(client.getOutputStream(), true);
    }

    catch(IOException io)
    {
        System.out.println("Client Handler not set up properly");
    }

}

public void run()
{
    // recieve request from the server
    String request = input.nextLine();

    System.out.println(request);
    // check the request
    while(!request.equals("close"))
    {
        // do whatever the user wants to do
        if (request.equals("get_inbox"))
        {
            System.out.println("INSIDE INBOX REQUEST");
        }
        else if (request.equals("send_email"))
        {
            System.out.println("INSIDE SEND EMAIL REQUEST");
        }

        request = input.nextLine(); // get new request from server
    }

    // end the client connection
    try
    {
        System.out.println("Ending connection");
        client.close();
    }
    catch(IOException io)
    {
        System.out.println("Coulnd't close connection");
    }

}


}

错误日志是:

at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8413)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at  com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at  com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run( GlassViewEventHandler.java:381)
at  com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run( GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at  com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354 (GlassViewEventHandler.java:417)
at   com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolki t.java:389)
at  com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewE ventHandler.java:416)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImp l.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
... 45 more
Caused by: java.lang.NullPointerException
at Client.validateUsername(Client.java:112)
at Client.loginButton(Client.java:99)
... 55 more

1 个答案:

答案 0 :(得分:0)

非常感谢James_D,因为outputToServer没有初始化。 正确的代码是:

    private void loader(){
    try
    {
        socket = new Socket(host, PORT);
        inputFromServer = new Scanner(socket.getInputStream());
        outputToServer = new PrintWriter(socket.getOutputStream(),true);

    }
    catch (IOException e)
    {

        e.printStackTrace();
        return;
    }

    if(this.outputToServer == null)
    {
        System.out.println("NULL OUTPUT TO SERVER");
    }
}

然后在loginButton中调用它:

   @FXML
private void loginButton(ActionEvent event) throws  IOException
{

    if (outputToServer == null)
        System.out.println("NULL IN LOGIN BUTTON FUNCTION");
    String t = Input.getText();
    //validateUsername(t);
    System.out.println(t);
    loader();
    validateUsername(t);
}