gpt4 book ai didi

java - 使用 Socket 发送和接收对象

转载 作者:行者123 更新时间:2023-12-01 09:36:36 25 4
gpt4 key购买 nike

我正在编写一个用于创建拍卖的小型客户端服务器应用程序。它适用于套接字,客户端应用程序和服务器应用程序交换两种对象 - 拍卖对象和客户端对象。客户端工作正常,但拍卖存在问题。当应用程序第一次发送特定拍卖时,效果很好,我们假设一等奖是 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);
}

最佳答案

Java 序列化保留了对象图的完整性,但代价是不重新传输已发送的对象,这可能会造成困惑。您需要查看 ObjectOutputStream.reset()ObjectOutputStream.writeUnshared() 以及它们存在的原因。

关于java - 使用 Socket 发送和接收对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38846929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com