我正在编写一个用于创建拍卖的小客户端 - 服务器应用程序。它适用于套接字,客户端应用程序和服务器应用程序正在交换2种对象 - 拍卖对象和客户端对象。客户端工作正常,但拍卖存在问题。当应用程序第一次发送一个特定的拍卖时它很好用,让我们告诉一等奖是100.00。其他客户收到此拍卖。但是当有人竞标时会出现一个镜像。我调试了连接,客户端应用程序正在发送带有新奖品的拍卖(110.00),但服务器接收旧奖品拍卖(100.00)。有什么可以解决这个问题?
以下是拍卖类:
public class Auction implements Comparable<Auction>, Serializable{
private Double prize;
private Item item;
private Client winner;
private Client owner;
public Auction(double prize, Item item, Client owner){
this.prize = prize;
this.item = item;
this.owner = owner;
this.winner = owner;
}
public Auction(double prize, Item item, Client owner, Client winner){
this.prize = prize;
this.item = item;
this.owner = owner;
this.winner = winner;
}
public void placeBid(double bidValue, Client winner){
double newPrize = prize + bidValue;
setWinner(winner);
setPrize(newPrize);
}
@Override
public int compareTo(Auction auction) {
int compare = prize.compareTo(auction.getPrize());
return compare;
}
public String toString(){
String value = String.format(item + " : %1$.2f | winner: " + winner, prize);
return value;
}
public double getPrize(){
return prize;
}
public Client getWinner(){
return winner;
}
public Client getOwner(){
return owner;
}
public Item getItem(){
return item;
}
public boolean equals(Object anAuction){
Auction auction = (Auction) anAuction;
Client testOwner = auction.getOwner();
Item testItem = auction.getItem();
String testItemName = testItem.getName();
String itemName = item.getName();
double testPrize = auction.getPrize();
return owner.equals(testOwner) && itemName.equals(testItemName);
}
private void setPrize(double prize){
this.prize = prize;
}
private void setWinner(Client winner){
this.winner = winner;
}
}
在客户端发送此拍卖的方法:
private void sendAuctions() throws IOException {
for(Auction auction : auctionList){
outputStream.writeObject("AUCTIONS");
outputStream.flush();
outputStream.writeObject(auction);
outputStream.flush();
}
}
以及在服务器端接收拍卖的方法:
private void receiveData() {
String receivedDataLabel = "";
try {
while (!receivedDataLabel.equals("END")) {
receivedDataLabel = (String) inputStream.readObject();
if (receivedDataLabel.equals("CLIENTS")) {
receiveClients();
} else if (receivedDataLabel.equals("AUCTIONS")) {
receiveAuctions();
} else if (receivedDataLabel.equals("CONNECTION_END")){
isConnected = false;
}
}
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
private void receiveAuctions() throws ClassNotFoundException, IOException {
Auction auction = (Auction) inputStream.readObject();
dataContainer.registerAuction(auction);
}
答案 0 :(得分:1)
Java序列化保留了对象图的完整性,可能会造成不重新传输已经发送的对象的费用。您需要查看ObjectOutputStream.reset()
或ObjectOutputStream.writeUnshared()
及其存在的原因。