[英]How to send multiple objects to socket in Java
Can anyone please advise how to send multiple serialized objects in java over a socket to a server? 任何人都可以建议如何通过套接字将Java中的多个序列化对象发送到服务器吗?
currently my server gets always only the first object. 目前,我的服务器始终只获得第一个对象。
Client side: 客户端:
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();
}
Server Side 服务器端
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();
}
The problem is on the server side, due to the call carSocket = CarServerSocket.accept();
由于调用carSocket = CarServerSocket.accept();
问题出在服务器端carSocket = CarServerSocket.accept();
being within the loop. 在循环中。 It should be done once before the loop, and you should then get the other objects: 应该在循环之前完成一次,然后您应该获取其他对象:
carSocket = CarServerSocket.accept();
while (true) {
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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.