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

标签 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 方法。当我尝试时,一个类似的 double 程序也成功了。

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

最佳答案

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

(而不是私有(private) BufferedWriter 输出;)

所有服务器:

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);

        });
    }



}

关于Javafx 服务器套接字 - 发送字符串消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52741466/

相关文章:

java - ConcurrentHashMap 和 Hash 表的区别

Windows 中的 Python 套接字问题 : socket. MSG_DONTWAIT

node.js - Node JS : How can I create a fake tcp socket for testing servers

java - 考虑到对象封装,getter 应该返回一个不可变的属性吗?

java - 如何通过单击按钮打开新窗口

java - 为什么我们需要一个 Runnable 来启动线程?

sockets - 套接字在读取之前可以在其缓冲区中存储多少数据?

java - C++中的内存映射文件用Java读取

java - Java 中如何将 ResultSet 转换为字符串

多线程问题