Sending an ArrayList <String> from the server side to the client side via TCP over the socket?

I am trying to send a single object from a server-side socket to a client socket via TCP. I can not understand where the problem is.

Here is the error I get on the client side:

java.io.EOFException at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2280) at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2749) at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:779) at java.io.ObjectInputStream.<init>(ObjectInputStream.java:279) at ClientSide.main(ClientSide.java:16) 

Code for server:

 import java.io.*; import java.net.*; import java.util.ArrayList; public class ServerSide { public static void main(String[] args) { try { ServerSocket myServerSocket = new ServerSocket(9999); Socket skt = myServerSocket.accept(); ArrayList<String> my = new ArrayList<String>(); my.set(0,"Bernard"); my.set(1, "Grey"); try { ObjectOutputStream objectOutput = new ObjectOutputStream(skt.getOutputStream()); objectOutput.writeObject(my); } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } } 

Code for the client side:

 import java.io.*; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; public class ClientSide { public static void main(String[] args) { try { Socket socket = new Socket("10.1.1.2",9999); ArrayList<String> titleList = new ArrayList<String>(); try { ObjectInputStream objectInput = new ObjectInputStream(socket.getInputStream()); //Error Line! try { Object object = objectInput.readObject(); titleList = (ArrayList<String>) object; System.out.println(titleList.get(1)); } catch (ClassNotFoundException e) { System.out.println("The title list has not come from the server"); e.printStackTrace(); } } catch (IOException e) { System.out.println("The socket for reading the object has problem"); e.printStackTrace(); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } 
+6
source share
1 answer

Switching from set to add does the trick

 ArrayList<String> my = new ArrayList<String>(); my.add("Bernard"); my.add("Grey"); 

ps. as others advise, this is not a good idea, but used only for training

+5
source

Source: https://habr.com/ru/post/927742/


All Articles