我想从我的服务器应用程序将同一个套接字上的两个不同对象发送到我的客户端应用程序。从我所读到的内容来看,我正在以正确的方式做到这一点,但我仍然无法将第二个对象发送给我的客户。
这是我的服务器代码:
public class ServerThread implements Runnable {
String name = null;
Socket socket = null;
public ServerThread(Socket s, String name) {
this.name = name;
this.socket = s;
}
@Override
public void run() {
try {
ObjectOutputStream serverOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream serverInputStream = new ObjectInputStream(socket.getInputStream());
RequestType request = (RequestType) serverInputStream.readObject();
switch (request) {
case LOGIN:
serverInputStream = new ObjectInputStream(socket.getInputStream());
RequestManager.manageLogin(serverOutputStream, serverInputStream);
serverOutputStream = new ObjectOutputStream(socket.getOutputStream());
RequestManager.managePopulateTable(serverOutputStream);
}
serverOutputStream.close();
serverInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是我的服务器请求管理器
public class RequestManager {
public static void manageLogin(ObjectOutputStream serverOutputStream, ObjectInputStream serverInputStream) {
ArrayList<ProductEntity> availableProducts = new ArrayList<>();
try {
UserEntity loggedUser = (UserEntity) serverInputStream.readObject();
if (DatabaseManager.userConnect(loggedUser.getUsername(), loggedUser.getPassword())) {
serverOutputStream.writeObject(loggedUser);
}
else
serverOutputStream.writeObject(null);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void managePopulateTable(ObjectOutputStream serverOutputStream) {
ArrayList<ProductEntity> availableProducts = DatabaseManager.getProducts();
try {
serverOutputStream.writeObject(availableProducts);
} catch (IOException e) {
e.printStackTrace();
}
}
}
当我尝试发送&#34; availableProducts&#34;对客户。
答案 0 :(得分:0)
您使用以下代码遇到了很多问题:
ObjectOutputStream serverOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream serverInputStream = new ObjectInputStream(socket.getInputStream());
...
switch (request) {
case LOGIN:
serverInputStream = new ObjectInputStream(socket.getInputStream());
...
serverOutputStream = new ObjectOutputStream(socket.getOutputStream());
当您打开ObjectOutputStream
时,标题信息将写入流以帮助管理对象序列化。同样,当您打开ObjectInputStream
时,将从流中读取标题信息。
但是在这里,你打开第二个ObjectInputStream
(它将从同一个套接字流中读取头信息)和第二个ObjectOutputStream
(它将头信息写入同一个套接字流)。因此,套接字上的对象流将处于错误状态 - 对象应遵循标头信息,而不是另一个对象流标头。
不要多次打开对象流。