[英]Javafx server socket - sending string message
Im doing the server/client messaging via server socket with javafx. 即时通讯通过使用javafx的服务器套接字执行服务器/客户端消息传递。
I have been doing this for a long time now and thought it would be simple enough but I cannot figure this out. 我已经这样做很长时间了,以为这很简单,但我无法弄清楚。 I have tried a bunch of different ways but I am just not good enough. 我尝试了很多不同的方法,但是我还不够好。 Please help me figure it out if you can. 如果可以的话,请帮我弄清楚。
Here is the code for client 这是客户端的代码
// 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');
}
}
and here is the code for server 这是服务器的代码
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);
});
}
I dont know if it is the problem with the datainputstream because It does not have a readline or readString method. 我不知道datainputstream是否存在问题,因为它没有readline或readString方法。 A similar program with double worked when I tried it out. 当我尝试时,类似的程序具有双重效果。
I am trying to make like a basic chatting window on both applications so that both can exchange messages. 我试图使这两个应用程序都像一个基本的聊天窗口,以便两者都可以交换消息。 when I press send in either of the applications, I expect the string to be sent to the other application. 当我在任何一个应用程序中按send时,我都希望将字符串发送到另一个应用程序。 Then I want to display that text in the text area in both the server and client, like how real chat behaves. 然后,我想在服务器和客户端的文本区域中显示该文本,就像真实聊天的行为一样。 Currently, the strings are shown in their own respective text areas but not the other application. 当前,字符串显示在其各自的文本区域中,而不显示在其他应用程序中。
At Server, you should use private DataOutputStream output;
在Server上,应该使用private DataOutputStream output;
and output.writeUTF(message);
和output.writeUTF(message);
and of course output = new DataOutputStream(socket.getOutputStream());
当然output = new DataOutputStream(socket.getOutputStream());
(and not private BufferedWriter output;
) (而不是private BufferedWriter output;
)
all Server: 所有服务器:
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);
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.