[英]Sending a PriorityQueue over Socket in Java sends an empty queue
我有兩個程序-服務器和客戶端。 基本上,服務器的工作是維護某個“項目”類的對象的ArrayList。 可以將項目添加到ArrayList中,也可以根據客戶端應用程序的請求更改現有項目。 有時,客戶端應用程序必須接收列表中包含的某些項目,而這些正是問題所在。 Item類具有其他對象(可序列化)的PriorityQueue作為實例變量。 問題在於,當服務器發送某些項目時,客戶端會接收所有內容,但每個項目的優先級隊列為空(正確接收了Item對象的所有其他實例變量)。
現在的代碼:
這是與問題相關的Item類的一部分:
public class Item implements Serializable
{
...Some instance variables...
PriorityQueue<Bid> pq;
public Item(...)
{
pq = new ProrityQueue<Bid>();
}
public void addStuff(Stuff bid)
{
this.pq.add(bid);
}
...other methods...
}
發送客戶端請求的ArrayList我只是在服務器端
ObjectOutputStream oos = new ObjectOutputStream(serverSocket.getOutputStream);
oos.writeObject(someArrayList<Item>);
在客戶端
ObjectInputStream ois = new ObjectInputStream(serverSocket.getInputStream);
ArrayList<Item> tempList = (ArrayList<Item>) ois.readObject();
我發現客戶端接收到它必須接收的每個對象及其所有實例變量(包括PriorityQueue),但PriorityQueue為空,這真的很奇怪。 為什么PriorityQueue中的對象是客戶端唯一未收到的東西? 關於通過套接字發送對象列表,其中包含其他對象的集合,我還應該了解一些其他信息嗎?
編輯 :我正在發布部分代碼以獲取更多詳細信息。 實際上,對於服務器與客戶端之間的通信,我使用ClientCommunications類和ServerCommunication類來處理所有內容,因此這兩個應用程序不必處理套接字。
發送一些我有客戶要求的物品
ArrayList<Item> list = handleItemsRequest(rim);
//this uses the server output stream to transfer an object to the client's output stream
comms.sendItems(list);
sendItems(list)方法的代碼:
public void sendItems(ArrayList<Item> items)
{
try
{
//oos is the output stream of the server socket
oos.writeObject(items);
}
catch (IOException e)
{
e.printStackTrace();
}
}
其中handleItemsRequest()是一種接受一些約束,然后僅返回與它們匹配的項目的方法:
public ArrayList<Item> handleItemsRequest(RequestItemsMessage rim)
{
//it is the new array list that consist of items matching the conditions
ArrayList<Item> it = new ArrayList<Item>();
//items is the arrayList maintained by the server
for (Item item : items)
{
if (item.matchesConditions)
{
it.add(item);
}
}
//it contains all the right items and the priorityQueue for each item has everything that it has to have
return it;
}
然后,客戶端應用通過調用來接收列表
//this comms variable is different from the one in the server and is a par of a different class
ArrayList<Item> list = comms.receiveItems();
receiveItems()的代碼:
public ArrayList<Item> receiveItems()
{
try
{
ArrayList<Item> list = (ArrayList<Item>) ois.readObject();
return list;
}
catch(ClassNotFoundException | IOException e)
{
e.printStackTrace();
}
return null;
}
現在,客戶端具有所有必須發送的項目,但它們的優先級隊列為空。
還有更多代碼,但是與這個問題無關,我不需要全部發布。
解決方案事實證明,在發送列表之前,必須重置服務器的OutputStream。 否則,客戶端將一次又一次地獲取舊實例。 非常感謝EJP指出了這個問題!
您曾經關閉流嗎? 嘗試在oos.close()
之后調用oos.close()
oos.writeObject()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.