I want to send an object(array) from a client to a server. I use the ObjectInputStream and the ObjectOutputStream. However, this invokes an error, that these methods are not defined in serverSocket class. 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; 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.
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.
Socket socket = new Socket( address, port );
ObjectOutputStream cO =
new ObjectOutputStream(socket.getOutputStream());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.