简体   繁体   English

如何在Java中的socketServer上接收对象

[英]How to receive an object on a socketServer in java

I want to send an object(array) from a client to a server. 我想将一个对象(数组)从客户端发送到服务器。 I use the ObjectInputStream and the ObjectOutputStream. 我使用ObjectInputStream和ObjectOutputStream。 However, this invokes an error, that these methods are not defined in serverSocket class. 但是,这将导致错误,即在serverSocket类中未定义这些方法。 How do I resolve the situation ??` 我该如何解决这种情况?

public int[] readResponse() throws IOException, ClassNotFoundException{
    int[] x = new int[5];



    ObjectOutputStream cO = new ObjectOutputStream(serverSocket.getOutputStream()); //here is the error
    ObjectInputStream cI = new ObjectInputStream(serverSocket.getInputStream()); // here is the error

    cO.writeObject(x); 

     x = (int[]) cI.readObject();
     for (int i = 0; i < 5; i++){
         System.out.println(x[i]);
     }
     return x;
    }

A java.net.ServerSocket is not meant to be used for actual input and output; java.net.ServerSocket不能用于实际的输入和输出。 it is a socket for listening on the server to incoming connection requests which are accepted, resulting in a java.net.Socket which is then the one for reading and writing. 它是一个套接字,用于在服务器上侦听已接受的传入连接请求,从而产生一个java.net.Socket,然后再进行读写。

Socket socket = serverSocket.accept();
ObjectInputStream cI = 
     new ObjectInputStream(socket.getInputStream());

On the client side, a java.net.Socket is created by calling the constructor and connected, via an address, to the client. 在客户端,通过调用构造函数来创建java.net.Socket并通过地址连接到客户端。

Socket socket = new Socket( address, port );
ObjectOutputStream cO =
     new ObjectOutputStream(socket.getOutputStream());

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

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