我的 Java 代码出现问题,FortuneClient2 成功连接到 FortuneServer2,但没有显示引述或作者。服务器使用 TXT 文件监听端口
28084
:src/assign3/fortunes.txt
我的 FortuneServer2 代码是:
package assign3;
import assign3.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
/**
* @author REMOVED
*/
public class FortuneServer2 {
private static final int PORT = 28084;
private static final String FILE_NAME = "src/assign3/fortunes.txt";
private List<FortuneEntry> fortunes;
public FortuneServer2() {
fortunes = new ArrayList<>();
readFortunes();
}
private void readFortunes() {
try (BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME))) { // open the file
String line = reader.readLine(); // read the first line
while (line != null) { // while there are more lines to read
if (line.startsWith("%")) { // if the line starts with a %, it's a fortune
String quote = ""; // initialize the quote
String author = ""; // initialize the author
line = reader.readLine(); // read the next line
while (line != null && !line.startsWith("%")) { // while there are more lines to read and the line doesn't start with a %
if (line.trim().startsWith("―") || line.trim().startsWith("—")) { // if the line starts with a dash, it's the author
author = line.trim(); // set the author
} else { // otherwise, it's part of the quote
quote += line; // add the line to the quote
}
line = reader.readLine(); // read the next line
}
fortunes.add(new FortuneEntry(quote.trim(), author)); // add the fortune to the list
} else {
line = reader.readLine(); // read the next line
}
}
} catch (IOException e) {
System.err.println("Error reading fortunes from file: " + e.getMessage()); // print an error message if there's an error reading the file
}
}
public void start() {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Fortune server started on port " + PORT);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected from " + clientSocket.getInetAddress());
// Read an integer value from the client
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
int index = in.readInt();
// Get the corresponding FortuneEntry object and send it to the client
FortuneEntry fortune = fortunes.get(index - 1); // Adjust for zero-based indexing
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
out.writeObject(fortune);
out.flush();
// Close the socket
clientSocket.close();
}
} catch (IOException e) {
System.err.println("Error starting Fortune server: " + e.getMessage());
}
}
public static void main(String[] args) {
FortuneServer2 server = new FortuneServer2();
server.start();
}
}
我的 FortuneClient2 代码是:
package assign3;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollBar;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
/**
* @author REMOVED
*/
public class FortuneClient2 extends Application {
private static final int SERVER_PORT = 28084;
private static final String SERVER_HOST = "localhost";
private static final int NUM_QUOTES = 50; // Change this to match the number of quotes in your file
private ScrollBar scrollBar;
private TextArea quoteArea;
private TextArea authorArea;
public void start(Stage stage) {
BorderPane root = new BorderPane();
Label quoteLabel = new Label("Quote:");
quoteArea = new TextArea();
quoteArea.setEditable(false);
Label authorLabel = new Label("Author:");
authorArea = new TextArea();
authorArea.setEditable(false);
scrollBar = new ScrollBar();
scrollBar.setMax(NUM_QUOTES - 1);
scrollBar.valueProperty().addListener((observable, oldValue, newValue) -> updateQuote((int) scrollBar.getValue()));
root.setTop(quoteLabel);
root.setLeft(quoteArea);
root.setCenter(authorLabel);
root.setRight(authorArea);
root.setBottom(scrollBar);
Scene scene = new Scene(root, 600, 400);
stage.setTitle("Fortune Client");
stage.setScene(scene);
stage.show();
connectToServer();
}
private void connectToServer() {
new Thread(() -> {
try (Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream())) {
System.out.println("Connected to FortuneServer2");
while (true) {
// Read the integer position from the scroll bar and send it to the server
int position = (int) scrollBar.getValue();
out.writeInt(position);
out.flush();
// Read the FortuneEntry object from the server and update the UI
FortuneEntry fortune = (FortuneEntry) in.readObject();
Platform.runLater(() -> updateUI(fortune));
}
} catch (IOException | ClassNotFoundException e) {
System.err.println("Error communicating with server: " + e.getMessage());
}
}).start();
}
private void updateUI(FortuneEntry fortune) {
quoteArea.setText(fortune.getQuote());
authorArea.setText(fortune.getAuthor() != null ? fortune.getAuthor() : "");
}
private void updateQuote(int position) {
// Update the quote and author text areas based on the selected position
}
public static void main(String[] args) {
launch(args);
}
}
最后,我的 FortuneEntry 代码是:
package assign3;
import java.io.Serializable;
/**
* @author REMOVED
*/
public class FortuneEntry implements Serializable {
private String quote;
private String author;
public FortuneEntry(String quote, String author) {
this.quote = quote;
if (author == null || author.isEmpty()) {
this.author = "";
} else {
this.author = author;
}
}
public String getQuote() {
return quote;
}
public String getAuthor() {
return author;
}
}
我首先查看了提供的
fortunes.txt
文件,以了解报价的内容:
%
Ada, n.: Something you need only know the name of to be an Expert in
computing. Useful in sentences like, "We had better develop an Ada
awareness."
%
Abandon hope, all ye who press "ENTER" here.
%
Ability is useless unless it is used.
― Robert Half
%
有些引用不包含作者,同时有些引用。因此,我在 FortuneServer2 中添加了
(line.trim().startsWith("―") || line.trim().startsWith("—"))
行,指示哪些行以破折号开头。如果他们这样做,他们包含一个作者。在我的 中这样做是有效的,但由于某种原因在我的新版本中没有,这让我不明白问题是什么,所以我可以解决这个问题。