I’m waiting for the data on the stream such a strange way… Because i think throwing exceptions each time stream tries readObject() is not a good idea. That’s why I use PushBackInputStream and read just one byte from that stream each 10 ms.
@Override
public void run() {
try {
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(
clientSocket.getOutputStream()));
oos.flush();
ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
PushbackInputStream pis = new PushbackInputStream(clientSocket.getInputStream());
while (true) {
int tempByte = -1;
if ((tempByte = pis.read()) == -1) {
sleep(10);
} else {
pis.unread(tempByte);
ArrayList<Object> arrList = (ArrayList<Object>) ois.readObject();
int command = (Integer) arrList.get(0);
if (command == CommandDescriptor.ADD_STRING.getCode()) {
String tempStr = (String) arrList.get(1);
boolean result = Server.colleciton.add(tempStr);
if (result) {
oos.writeInt(1);
oos.flush();
} else {
oos.writeInt(0);
oos.flush();
}
} else if (command == CommandDescriptor.REMOVE_STRING.getCode()) {
...
I do something wrong with streams… I get an exception:
Exception in thread "Thread-0" java.lang.ClassCastException: java.io.ObjectStreamClass cannot be cast to java.util.ArrayList
at com.rizhov.main.ClientHandler.run(ClientHandler.java:39)
At that part of code:
ArrayList<Object> arrList = (ArrayList<Object>) ois.readObject();
What am I doing wrong? Is there any better solution to wait a data.
UPDATE:
ArrayList<Object> arrList = null;
for (;;) {
try {
arrList = ((ArrayList<Object>) ois.readObject());
break;
} catch (Exception e) {
}
}
int command = (Integer) arrList.get(0);
You can only wrap a Stream once. If you wrap it multiple times you are more likely to get confused than it be useful.
Once a stream has closed it won’t re-open so reading a character to check if the stream has finished and discarding it is not very useful. Sleeping when the operation would block anyway is not very useful either.
Instead of using
Integercodes I would use enum values. This will be cleaner and you will be able to use a switch statement.