任何人都可以請指教如何通過套接字將多個序列化的對象以java的形式發送到服務器?
目前我的服務器始終只有第一個對象。如何在Java中將多個對象發送到套接字
客戶端:
public void communicate() throws UnknownHostException, IOException {
carClientSocket = new Socket("localhost", 4444);
carClientOR = new ObjectOutputStream(carClientSocket.getOutputStream());
Car[] CarList = new Car[11];
for (int i = 1; i <=10; i++) {
//Car alpha;
CarList[i] = new Car("Alpha Romeo","GTI",1999+i);
}
for (int i =1; i<= 10; i++) {
carClientOR.writeObject(CarList[i]);
carClientOR.flush();
//carClientOR.reset();
}
carClientSocket.close();
}
服務器端
public void communicate() throws IOException, ClassNotFoundException {
CarServerSocket = new ServerSocket(4444);
System.out.println("Server is ready and waiting for connection from client..\n");
while (true) {
carSocket = CarServerSocket.accept();
System.out.println("Server Connected");
carServerIR = new ObjectInputStream(carSocket.getInputStream());
Car alpha1 = (Car) carServerIR.readObject();
System.out.println("Object received from car clinet: " + alpha1.getCarBrad() + " " + alpha1.getCarModel() + " " + alpha1.getCarYear());
}
//carSocket.close();
//CarServerSocket.close();
}
是的......那是因爲你只讀一次......你需要一個循環來閱讀。 'while((object = input.readObject())!= null)'這就是你應該怎麼做的模板 – 3kings
BRAVOֱ!在服務器端使用for循環完美工作。我會嘗試一下想法..非常感謝! – Asfbar
沒問題,只要確保在客戶端你需要'output.writeObject(null)'當你想結束閱讀,所以循環踢出 – 3kings