【问题标题】:Javafx server socket - sending string messageJavafx 服务器套接字 - 发送字符串消息
【发布时间】:2019-03-15 10:31:24
【问题描述】:

我正在使用 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 方法。我试用了一个类似的双重程序。

我正在尝试在两个应用程序上制作一个基本的聊天窗口,以便两者都可以交换消息。当我在任一应用程序中按发送时,我希望将字符串发送到另一个应用程序。然后我想在服务器和客户端的文本区域中显示该文本,就像真正的聊天行为一样。目前,字符串显示在各自的文本区域中,但不显示在其他应用程序中。

【问题讨论】:

  • 您的问题是什么?预期的行为是什么,你得到的行为是什么?
  • 哦,对不起,我什至忘了问实际问题。我正在尝试在两个应用程序上制作一个基本的聊天窗口,以便两者都可以交换消息。双向通信。我也会编辑帖子。
  • 重复 Koray 的问题:预期的行为是什么,你得到的行为是什么?
  • 添加了预期的行为和我得到的行为。对不起。

标签: java multithreading sockets javafx server


【解决方案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);

        });
    }



}

【讨论】:

  • 这适用于服务器端。客户端的消息显示在服务器端。服务器的消息仍然没有显示在客户端。我认为这与我如何在客户端创建线程以及其中的内容有关。
  • 好的。对不起。我真笨。我将文本附加到文本字段而不是文本区域。修复了它,现在它可以工作了。非常感谢。
猜你喜欢
  • 2015-06-21
  • 1970-01-01
  • 2018-09-24
  • 1970-01-01
  • 1970-01-01
  • 2020-08-20
  • 1970-01-01
  • 2015-01-09
  • 1970-01-01
相关资源
最近更新 更多