开发者

Java Sockets - receiving but not what was sent!

I've been trying to debug this for 2 hours and i just can't explain it. I have a server and a client. (server manages some Auctions).

What happens:

  1. The client request something , server sends data back and client receives it just fine.

  2. The client sends something to the server, and the server updates some data.

  3. The client makes the same request as first time (1.), the server send back the updated data, but the client does not receive the new update data, instead it receives the old data (as it got it in the first request (1.).

The data that is being sent is just a Java Bean with two List-s. And the code:

 // CLIENT CLASS
// creates socket, sends and listens on the socket
// listening is done on a separate thread
public class ServerConnector {

private Socket socket = null;
private ObjectOutputStream out = null;
private Display display;
private ServerListener listener;
public ServerConnector(Display display) {
    this.display = display;
        try {
            socket = new Socket("localhost",33333);
            out = new ObjectOutputStream(socket.getOutputStream());
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        listener = new ServerListener(socket, display);
        new Thread(listener).start();


}



public void sendRequest(Request request) {
    try {
        out.writeObject(request);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

class ServerListener implements Runnable {
    private Socket socket;
    private ObjectInputStream in = null;
    private Display display;
    public ServerListener(Socket socket,Display display) {
        this.socket = socket;
        this.display = display;
        try {
            in = new ObjectInputStream(socket.getInputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        Response response =null;

        try {
            while ((response = (Response)in.readObject()) != null) {
                if (response.getCars().size() > 0) {
                    display.showAvailableCars(response.getCars());
                }
                if(response.getAucs().size() > 0) {
                    List<Auction> auctionz  = response.getAucs();//HERE 1st time it gets the GOOD data, 2nd time should get UPDATED DATA but instead receives the OLD DATA (same as 1st time).
                    display.showOpenAuctions(auctionz);
                }
                response = null;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

}
//CLIENT CLASS
// controls when something should be sent, and print out responses
public class Display {
Scanner console = new Scanner(System.in);
ServerConnector server = new ServerConnector(this);
List<Car> cars;
List<Auction> aucs;

public void show开发者_C百科() {
    int opt = 0;
        System.out.println("1. Show available cars for auction.");
        System.out.println("2. Show open auctions.");
        opt = console.nextInt();
        Request request = new Request();
        if (opt == 1)
            request.setRequest(Request.GET_CARS);
        if (opt == 2) {
            request.setRequest(Request.GET_OPEN_AUCTIONS);
        }
        server.sendRequest(request);

    }


public void showAvailableCars(List<Car> cars) {
    int i = 0;
    for (Car c : cars ){
        i++;
        System.out.println(i +". " + c.getMaker() + " " + c.getModel() + " price: " + c.getPrice());
    }
    System.out.println("Select car to open Auction for:");
    int selectedCar = console.nextInt();
    if (selectedCar != 0) {
        if (selectedCar <= cars.size()) {
            Request request= new Request();
            request.setRequest(Request.OPEN_AUCTION);
            Car c = cars.get(selectedCar-1);
            request.setCar(c);
            server.sendRequest(request);
        }
    }
    show();
}


public void setCars(List<Car> cars) {
    this.cars = cars;

}


public void showOpenAuctions(List<Auction> aucs2) {
    int i = 0;
    for (Auction auc : aucs2) {
        i++;
        System.out.println(i+ ". " + auc.getCar().getModel() + " " + auc.getCar().getMaker() + " last price: " + auc.getPrice());
    }
    System.out.println("You can now make offers");
    System.out.println("Input auction number:");
    int selectedAuction = 0;
    selectedAuction = console.nextInt();
    if (selectedAuction > 0 && selectedAuction <= aucs2.size()) {
        System.out.println("Offer new price:");
        int price = console.nextInt();
        Request request= new Request();
        request.setRequest(Request.MAKE_OFFER);
        request.setAuctionId(aucs2.get(selectedAuction-1).getId());
        request.setPrice(price);
        server.sendRequest(request);
    }
    show();

}


public void setOpenAuctions(List<Auction> aucs2) {
    this.aucs = aucs2;

}

}
// SERVER CLASS : send and receives
public class ClientManager implements Runnable {

private AuctionManager manager = new AuctionManagerImpl();
private Socket client;
private ObjectInputStream in = null;
private ObjectOutputStream out = null;


public ClientManager(Socket socket) {
    this.client = socket;
     try {
          in = new ObjectInputStream(client.getInputStream());
          out = new ObjectOutputStream(client.getOutputStream());
     } catch(Exception e1) {
             try {
                 e1.printStackTrace();
                client.close();
       }catch(Exception e) {
               System.out.println(e.getMessage());
             }
             return;
         }
}

@Override
public void run() {
    Request req = null;
    try {
            while ((req = (Request)in.readObject()) != null) {
                if (req.getRequest() != null) {
                    if (req.getRequest().equals(Request.GET_CARS)) {
                        Response response = new Response();
                        response.setCars(manager.getAvailableCars());
                        out.writeObject(response);
                        continue;
                    }

                    if (req.getRequest().equals(Request.OPEN_AUCTION)) {
                        manager.openAuction(req.getCar());
                        continue;
                    }

                    if (req.getRequest().equals(Request.GET_OPEN_AUCTIONS)) {
                        Response response = new Response();
                        response.setAucs(manager.getHoldedAuctions()); //this line ALWAYS sends to the client GOOD, UPDATED DATA

                        out.writeObject(response);
                        out.flush();
                        continue;
                    }
                    if (req.getRequest().equals(Request.MAKE_OFFER)) {
                        Auction auction = manager.getOpenAuction(req.getAuctionId());
                        manager.updateAuction(auction, req.getPrice(),client.getRemoteSocketAddress().toString());
                        continue;
                    }
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}


It could be because you are using ObjectOutputStreams. Remember that ObjectOutputStreams will cache all objects written to them so that if the same object is written again in the future it can write a back-reference instead of re-writing the whole object. This is necessary when writing an Object graph.

Your code fragment:

if (req.getRequest().equals(Request.GET_CARS)) {
    Response response = new Response();
    response.setCars(manager.getAvailableCars());
    out.writeObject(response);
    continue;
}

is writing the object returned by manager.getAvailableCars(). The next time a request is received the same object (but now with different contents) is written - but the ObjectOutputStream doesn't know about the new contents so it just writes a back-reference. The ObjectInputStream at the other end sees the back-reference and returns the same object it read last time, i.e. the original data.

You can fix this by calling ObjectOutputStream.reset() after each response. This will clear the stream's cache.


See ObjectOutputStream.writeUnshared() and .reset().


Ok. I just found out the solution. from here http://java.sun.com/developer/technicalArticles/ALT/sockets/ :

Object Serialization Pitfall

When working with object serialization it is important to keep in mind that the ObjectOutputStream maintains a hashtable mapping the objects written into the stream to a handle. When an object is written to the stream for the first time, its contents will be copied to the stream. Subsequent writes, however, result in a handle to the object being written to the stream. This may lead to a couple of problems:

If an object is written to the stream then modified and written a second time, the modifications will not be noticed when the stream is deserialized. Again, the reason is that subsequent writes results in the handle being written but the modified object is not copied into the stream. To solve this problem, call the ObjectOutputStream.reset method that discards the memory of having sent an object so subsequent writes copy the object into the stream. An OutOfMemoryError may be thrown after writing a large number of objects into the ObjectOutputStream. The reason for this is that the hashtable maintains references to objects that might otherwise be unreachable by an application. This problem can be solved simply by calling the ObjectOutputStream.reset method to reset the object/handle table to its initial state. After this call, all previously written objects will be eligible for garbage collection. The reset method resets the stream state to be the same as if it had just been constructed. This method may not be called while objects are being serialized. Inappropriate invocations of this method result in an IOException.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜