您好我正在编写一个应用程序,其中客户端向服务器发送房间名称,服务器创建它,然后发送回整个房间列表。从服务器接收此对象时遇到问题,当我关闭客户端时也会感兴趣。应用程序并再次打开我有房间列表就像它应该是。我在客户端应用程序中刷新房间列表,但它总是空的只有重新打开有助于这很奇怪,我不知道这个问题。
在客户端:
getIs() method is returning is object
getOs() method returning os object
this.os = new ObjectOutputStream(clientSocket.getOutputStream());
this.is = new ObjectInputStream(clientSocket.getInputStream());
private void createRoom(ActionEvent event) {
String roomName = "CreateRoom ";
roomName += setRoomName();
String response = null;
try {
client.getOs().writeObject(roomName);
response = (String) client.getIs().readObject();
System.out.println(response);
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void refreshRooms() {
String response = null;
try {
client.getOs().writeObject("RefreshRooms");
response = (String) client.getIs().readObject();
System.out.println(response);
rooms = (Rooms) client.getIs().readObject();
System.out.println("Print in client: ");
rooms.printAllRooms();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
服务器:
this.os = new ObjectOutputStream(connection.getOutputStream());
this.is = new ObjectInputStream(connection.getInputStream());
public void run() {
String inputRequest = null;
try {
while((inputRequest = (String) ois.readObject()) != null) {
System.out.println(inputRequest);
handleRequest(inputRequest);
}
} catch (IOException | ClassNotFoundException e) {
System.out.println("Client has disconnected.");
e.printStackTrace();
}
}
private void handleRequest(String request) {
String response = null;
String[] msg = request.split(" ");
if(msg[0].equals("CreateRoom")) {
try {
oos.writeObject("You want create a room.");
Room newRoom = new Room(msg[1]);
rooms.addRoom(newRoom);
System.out.println("Created room: " + newRoom.getName());
System.out.println("\n Print after creation: ");
rooms.printAllRooms();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if (msg[0].equals("RefreshRooms")) {
try {
oos.writeObject("You want list of rooms.");
System.out.println("Print before send.");
rooms.printAllRooms();
oos.writeObject(rooms);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
///编辑: 所以我删除了PrintWriter和BufferedReader对象,现在我只使用了Object Streams。现在不起作用的是:
我一个接一个地创建一些房间,然后在客户端应用程序上刷新房间列表 - 在这种情况下,我得到所有房间
但是当我创建一个房间刷新然后创建另一个房间并刷新我在第二次刷新后只获得一个房间,所以基本上当我刷新服务器时总是从第一次发送给我发送相同的对象而我不知道如何更改它
此外,我在服务器端打印这些房间,并始终获得所有房间,以便创建房间。
答案 0 :(得分:0)
您可以尝试flush缓冲的流:
os.flush()
这将强制流实际发送序列化对象的字节。如果不这样,BufferedOutputStream
可能只是等待并缓冲数据,正如名称所示。这样做是为了使发送的数据包的大小不会变得太小,如果你想发送多个对象,这将导致很多开销。
如果你完成了,你应该关闭流。