Javafx服务器套接字-发送字符串消息

时间:2018-10-10 13:33:51

标签: java multithreading sockets javafx server

我正在使用javafx通过服务器套接字进行服务器/客户端消息传递。

我已经这样做很长时间了,以为这很简单,但是我无法弄清楚。我尝试了很多不同的方法,但是我还不够好。如果可以的话,请帮我弄清楚。

这是客户

的代码
    // IO streams
        DataOutputStream toServer = null;
        DataInputStream fromServer = null;
        String serverMessage = "";

  @Override // Override the start method in the Application class
  public void start(Stage primaryStage) {
    // Panel p to hold the label and text field
    BorderPane paneForTextField = new BorderPane();
    Button btnSend = new Button("|>");
    paneForTextField.setPadding(new Insets(5, 5, 5, 5)); 
    paneForTextField.setStyle("-fx-border-color: green");
    paneForTextField.setRight( btnSend );

    TextField tf = new TextField();
    tf.setAlignment(Pos.BOTTOM_RIGHT);
    paneForTextField.setCenter(tf);

BorderPane mainPane = new BorderPane();
// Text area to display contents
TextArea ta = new TextArea();
mainPane.setTop(new ScrollPane(ta));
mainPane.setCenter(paneForTextField);

// Create a scene and place it in the stage
Scene scene = new Scene(mainPane, 450, 270);
primaryStage.setTitle("Client"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage

tf.setOnAction(e -> {
  try {
    // Get the message from the text field
    String message = tf.getText().trim();

    // Send the message to the server
    toServer.writeBytes(message);
    toServer.flush();
    System.out.println("message sent");
    tf.setText("");

    // Display to the text area
    ta.appendText("client: " + message + "\n");


  }
  catch (IOException ex) {
    System.err.println(ex);
  }
});

try {
  // Create a socket to connect to the server
  Socket socket = new Socket("localhost", 8000);
  // Socket socket = new Socket("130.254.204.36", 8000);
  // Socket socket = new Socket("drake.Armstrong.edu", 8000);

  // Create an input stream to receive data from the server
  fromServer = new DataInputStream( socket.getInputStream() );

  // Create an output stream to send data to the server
  toServer = new DataOutputStream( socket.getOutputStream() );


  new Thread(() -> {
    try{
        while(true){
            serverMessage = fromServer.readUTF();

            System.out.println("message received");

            Platform.runLater( () -> {

                tf.appendText(serverMessage);

            });


        }
    }
    catch(IOException e){
        ta.appendText(e.toString() + "\n");
    }

  }).start();
}
catch (IOException ex) {
  ta.appendText(ex.toString() + '\n');
}
  }

这是服务器

的代码
private TextField tf = new TextField();
    private ServerSocket serverSocket;
    private Socket socket;
    private DataInputStream input ;
    private BufferedWriter output;
    // Text area for displaying contents
    TextArea ta = new TextArea();

    @Override // Override the start method in the Application class
    public void start(Stage primaryStage) {


         // Create a server socket
        BorderPane borderPaneForText = new BorderPane();
        Button btnSend = new Button("|>");
        btnSend.setOnAction( e-> {

            Platform.runLater( () -> {
                try{

                    output.write(tf.getText());
                    showMessage("server: " + tf.getText() + "\n");

                }
                catch(IOException ex){
                    ex.printStackTrace();
                }
            });
        });

        tf.setAlignment(Pos.BOTTOM_RIGHT);

        borderPaneForText.setCenter(tf);
        borderPaneForText.setRight(btnSend);
        borderPaneForText.setPadding( new Insets( 5, 5, 5, 5) );

        BorderPane mainPane = new BorderPane();
        mainPane.setTop(new ScrollPane(ta));
        mainPane.setCenter(borderPaneForText);

        // Create a scene and place it in the stage
        Scene scene = new Scene(mainPane, 450, 270);
        primaryStage.setTitle("Server"); // Set the stage title
        primaryStage.setScene(scene); // Place the scene in the stage
        primaryStage.show(); // Display the stage

        ta.setEditable(false);
        new Thread( () -> {
            try {
              // Create a server socket
              serverSocket = new ServerSocket(8000);
              Platform.runLater(() ->
                ta.appendText("Server started at " + new Date() + '\n'));

              // Listen for a connection request
              Socket socket = serverSocket.accept();

              // Create data input and output streams
              input = new DataInputStream( socket.getInputStream() );
              output = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream() ) );

              while (true) {
                // Receive message from the client
                String message = input.readUTF();

                output.write(message);

                Platform.runLater(() -> {
                  ta.appendText("Client: " + message + "\n"); 
                });
              }
            }
            catch(IOException ex) {
              ex.printStackTrace();
            }
        }).start();
    }

        /**
         * The main method is only needed for the IDE with limited
         * JavaFX support. Not needed for running from the command line.
         */
        public static void main(String[] args) {
          launch(args);
        }




  public void showMessage(String message){

      Platform.runLater( () -> {
              ta.appendText(message);

      });
  }

我不知道datainputstream是否存在问题,因为它没有readline或readString方法。当我尝试过时,类似的程序具有双重效果。

我试图使这两个应用程序都像一个基本的聊天窗口,以便两者都可以交换消息。当我在任何一个应用程序中按send时,我都希望将字符串发送到另一个应用程序。然后,我想在服务器和客户端的文本区域中显示该文本,就像真实聊天的行为一样。当前,字符串显示在它们自己的文本区域中,而不显示在其他应用程序中。

1 个答案:

答案 0 :(得分:1)

在服务器上,您应该使用private DataOutputStream output;output.writeUTF(message);,当然也要使用output = new DataOutputStream(socket.getOutputStream());

(而不是private BufferedWriter output;

所有服务器:

public class Main extends Application {

    private TextField tf = new TextField();
    private ServerSocket serverSocket;
    private Socket socket;
    private DataInputStream input ;
    private DataOutputStream output;
    // Text area for displaying contents
    TextArea ta = new TextArea();

    @Override // Override the start method in the Application class
    public void start(Stage primaryStage) {


        // Create a server socket
        BorderPane borderPaneForText = new BorderPane();
        Button btnSend = new Button("|>");
        btnSend.setOnAction( e-> {

            Platform.runLater( () -> {
                try{

                    output.writeUTF(tf.getText());
                    showMessage("server: " + tf.getText() + "\n");

                }
                catch(IOException ex){
                    ex.printStackTrace();
                }
            });
        });

        tf.setAlignment(Pos.BOTTOM_RIGHT);

        borderPaneForText.setCenter(tf);
        borderPaneForText.setRight(btnSend);
        borderPaneForText.setPadding( new Insets( 5, 5, 5, 5) );

        BorderPane mainPane = new BorderPane();
        mainPane.setTop(new ScrollPane(ta));
        mainPane.setCenter(borderPaneForText);

        // Create a scene and place it in the stage
        Scene scene = new Scene(mainPane, 450, 270);
        primaryStage.setTitle("Server"); // Set the stage title
        primaryStage.setScene(scene); // Place the scene in the stage
        primaryStage.show(); // Display the stage

        ta.setEditable(false);
        new Thread( () -> {
            try {
                // Create a server socket
                serverSocket = new ServerSocket(8000);
                Platform.runLater(() ->
                        ta.appendText("Server started at " + new Date() + '\n'));

                // Listen for a connection request
                Socket socket = serverSocket.accept();

                // Create data input and output streams
                input = new DataInputStream( socket.getInputStream() );
                output = new DataOutputStream(socket.getOutputStream());

                while (true) {
                    // Receive message from the client
                    String message = input.readUTF();

                    output.writeUTF(message);
                    Platform.runLater(() -> {
                        ta.appendText("Client: " + message + "\n");
                    });
                }
            }
            catch(IOException ex) {
                ex.printStackTrace();
            }
        }).start();
    }

    /**
     * The main method is only needed for the IDE with limited
     * JavaFX support. Not needed for running from the command line.
     */
    public static void main(String[] args) {
        launch(args);
    }




    public void showMessage(String message){

        Platform.runLater( () -> {
            ta.appendText(message);

        });
    }



}
相关问题