我正在以一种奇怪的方式等待流上的数据......因为我认为每次流尝试时抛出异常readObject()
并不是一个好主意。这就是为什么我每 10 毫秒使用PushBackInputStream
并从该流中读取一个。byte
@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()) {
...
我对流做错了什么......我得到了一个例外:
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)
在代码的那部分:
ArrayList<Object> arrList = (ArrayList<Object>) ois.readObject();
我究竟做错了什么?有没有更好的解决方案来等待数据。
更新:
ArrayList<Object> arrList = null;
for (;;) {
try {
arrList = ((ArrayList<Object>) ois.readObject());
break;
} catch (Exception e) {
}
}
int command = (Integer) arrList.get(0);