java.io.EofException误差与httphandler对象序列化



我正在尝试在HttpHandler类中序列化对象。

我有2个文件, Server3.java

package server3;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Server3 {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(3333), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
        String response = "Kjo eshte nje pergjigje nga serveri! n";
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
        Personat obj = new Personat();
        ObjectOutputStream objOut = new     ObjectOutputStream(t.getResponseBody());
        objOut.writeObject(obj);
        objOut.close();
}
}
}
class Personat implements Serializable{
private static final long serialVersionUID = 1L;
int ID=3;
String Name="Andi";
}

Client3.java

package server3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
//te gjithe personat qe jan ne database me nej objekt 
public class Client3 {
public static void main(String[] args) throws Exception {
    try {
        URL url = new URL("http://localhost:3333");
        HttpURLConnection s = (HttpURLConnection) url.openConnection();
        s.setDoOutput(true);
        s.setDoInput(true);
        s.setRequestMethod("POST");
        s.setUseCaches(false);
        InputStream in = s.getInputStream();
        InputStreamReader isr = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(isr);
        int c;
        while ((c = br.read()) != -1) {
            System.out.print((char) c);
        }
        ObjectInputStream ios = new ObjectInputStream(s.getInputStream());
        Personat oin = (Personat) ios.readObject();
        String emri=oin.Name;
        System.out.println(emri);
        ios.close();
        s.disconnect();
    } catch (IOException ex) {
        System.err.println(ex);
        System.out.print(ex);
    }
}
  }

,但是当我运行时,Eclipse向我展示

java.io.EOFException Kjo eshte nje pergjigje nga serveri! njava.io.EOFException`

我不明白为什么。

问题是您试图将字符串response和对象同时拟合到response.length()字节中。发生的事情是仅发送response.length()字节,因此,如果您尝试阅读更多信息,您将获得EOFException

如果您将responseLength参数设置为0,则它将允许您传输任意数量的数据

t.sendResponseHeaders(200, 0); 

如果要在其中写更多数据,也不应关闭流。在所有写作完成之前,请勿致电os.close()

相关内容

  • 没有找到相关文章

最新更新