用java将对象从客户机发送到服务器

zkure5ic  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(378)

如何在java中向服务器发送对象?
客户:

Help h = new Help("Mattia Cammalleri","Informatica","18 Novembre 2020");

    Socket s = new Socket("localhost", 8888);
    ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream()); 
    ObjectInputStream is = new ObjectInputStream(s.getInputStream());
    os.writeObject(h);
    os.flush();

服务器:

ServerSocket ss = new ServerSocket(8888);
    Socket s = ss.accept(); 
    ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream()); 
    ObjectInputStream is = new ObjectInputStream(s.getInputStream());
    Help h = (Help) is.readObject();
    System.out.println("Richiesta " + h);

对象(实现可序列化):

public String alunno;
public String materia;
public String data;

为什么不起作用?

egdjgwm8

egdjgwm81#

我是这样解决的:
客户:

Help h = new Help("Mattia Cammalleri","Informatica","18 Novembre 2020");
    Socket socket = new Socket("localhost", 7777);
    System.out.println("Connected");
    OutputStream outputStream = socket.getOutputStream();
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
    System.out.println("The object has been sent");
    objectOutputStream.writeObject(h);
    socket.close();

服务器:

ServerSocket ss = new ServerSocket(7777);
    System.out.println("Waiting for the client");
    Socket socket = ss.accept();
    System.out.println("Connected from " + socket + "!");
    InputStream inputStream = socket.getInputStream();
    ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
    Help h = (Help) objectInputStream.readObject();
    System.out.println("Object: " + h);
    ss.close();
    socket.close();

相关问题