简体   繁体   English

如何在Java中的服务器套接字中处理不同的响应类型

[英]how to handle different response type in server socket in java

I have just started learning java. 我刚刚开始学习Java。 I have two projects that implement server socket. 我有两个实现服务器套接字的项目。 In server project, the server is responds based on an operation name that client send. 在服务器项目中,服务器根据客户端发送的操作名称进行响应。 Operations are dir - send server directory files (File[]) cd - current directory name (String) 操作是dir-发送服务器目录文件(File [])cd-当前目录名(String)

Server.java 服务器.java

Socket client = serverSocket.accept();
DataInputStream in = new DataInputStream(client.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
String operation = in.readUTF();
System.out.println("Performing opration : " + operation);
switch (operation) {
    case "dir":
        File[] lstOfFiles = folder.listFiles();
        out.writeObject(lstOfFiles);
        break;
    case "cd":
        out.writeObject(new String("Current Directory : " + currentDir));
        break;

} }

Now how can I identify on the client side what is the object of type ? 现在如何在客户端识别什么是类型的对象?

Client.java 客户端.java

ObjectInputStream in = new ObjectInputStream(client.getInputStream());
File[] lstOfFiles = (File[]) in.readObject();
if(lstOfFiles !=null)
    System.out.println("Total : " + lstOfFiles.length);

But this is throwing exception ClassCastException. 但这会引发ClassCastException异常。 Then I tried 然后我尝试

if ((in.readObject()).getClass() == String.class) {
   System.out.println((String)in.readObject());
}
else if (in.readObject().getClass() == Object.class) {
   File[] lstOfFiles = (File[]) in.readObject();
   if(lstOfFiles !=null)
      System.out.println("Total : " + lstOfFiles.length);
}

Then this is showing EOFException. 然后,这显示EOFException。 How can I solve this? 我该如何解决? or any better approach ? 还是更好的方法?

Every object in Java extends Object class, so your condition is unable to differ what you are trying to recognize. Java中的每个对象都扩展了Object类,因此您的条件无法改变您试图识别的内容。 Also, you need to check if an object was returned from stream, right now you are just working on object that is possibly null. 另外,您需要检查对象是否从流中返回,现在您正在处理可能为null的对象。

if you use 如果您使用

in.readObject()

then after using this will empty the stream.So that's why it is throwing EOFException. 然后使用它会清空流。这就是为什么它抛出EOFException的原因。

I have solved using this 我已经解决了使用这个

Object response = in.readObject();
if(response.getClass() == String.class){
   // code to run
}
else {
   // code to run
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM