如何在Java中将客户端的对象发送到服务器?

时间:2015-06-12 21:54:07

标签: java object stream client server

您好我想用Java测试客户端和服务器之间的连接。例如,我想从客户端向服务器发送一个对象。该对象是我构建的用户。

如果我启动服务器和客户端,我会收到此错误:

  run:
java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:209)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at java.net.SocketInputStream.read(SocketInputStream.java:223)
    at java.io.ObjectInputStream$PeekInputStream.peek(ObjectInputStream.java:2296)
    at java.io.ObjectInputStream$BlockDataInputStream.peek(ObjectInputStream.java:2589)
    at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2599)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1319)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
    at taraticketclienttest.TaraTicketClientTest.main(TaraTicketClientTest.java:37)
BUILD SUCCESSFUL (total time: 0 seconds)

这是我的客户:

public static void main(String[] args) throws ClassNotFoundException {

        try(Socket socket = new Socket("localhost", 7778)) {

            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

            User u = new User("Wowa");

            out.writeObject(u);

            User u2 = (User)in.readObject();

            System.out.println(u2.getName());


        } catch (IOException ex) {
          ex.printStackTrace();
        }
    }

这是我的服务器:

public class DemoServer {
public static void main(String[] args) throws ClassNotFoundException {
    try(ServerSocket serverSocket = new ServerSocket(7778)) {

        while (true) {                
            Socket clientSocket = serverSocket.accept();
            System.out.println("socket open...");

            ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
            ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());

            User u = (User) in.readObject();

            System.out.println(u.getName());

            out.writeObject(u);
        }

    } catch (IOException ex) {
      ex.printStackTrace();
    }
}

}

这是我的用户:

public class User implements Serializable {
private String name; 

public User(){}

public User(String name){
    this.name = name;
}

public String getName(){
    return this.name;
}

}

2 个答案:

答案 0 :(得分:1)

您需要班级User来实施Serializable

public class User implements Serializable {
    ...
}

除非ObjectInputStream实施ObjectOutputStream

,否则无法将对象写入/读取SerializableSSLEngine On SSLCertificateFile /etc/ssl/localcerts/example_com.crt SSLCertificateKeyFile /etc/ssl/localcerts/example.com.key SSLCACertificateFile /etc/ssl/localcerts/example.com.chain.crt

答案 1 :(得分:1)

作为替代方案,您可以使用https://www.jetbrains.com/upsource/help/2.0/proxy_configuration.htmlJackson以JSON格式将对象作为String发送。它们肯定比defalut java对象序列化更快(并且你不需要使类Serializable)

您可以在以下链接中使用jackson获取有关JSON-Object序列化的更多信息 Boon