Is it possible to pass an ArrayList via a Socket ( OutputStreamWriter ), if so, how?

There is a list on the server and it must be transferred to the client.

  • to convert to a stream of bytes and on the client to consider? - GenCloud

1 answer 1

Yes you can.

Send:

 try { ServerSocket serverSocket = new ServerSocket(1234); Socket socket = serverSocket.accept(); ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("Hello"); arrayList.add("world"); try { ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream()); objectOutputStream.writeObject(arrayList); } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } 

Accept:

 try { Socket socket = new Socket("server_ip", 1234); ArrayList<String> arrayList = new ArrayList<String>(); try { ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream()); try { Object object = objectInputStream.readObject(); arrayList = (ArrayList<String>) object; System.out.println(arrayList.toString()); } catch (ClassNotFoundException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 
  • A null pointer exception crashes, but I'll still test it - Dmitriy Mironov
  • I spent a test on my application and on your example and in both cases the same error crashes: java.net.SocketException: Connection reset. - Dmitriy Mironov
  • @DmitriyMironov; For clarity, I also added the output of the result: System.out.println(arrayList.toString()); . On my local machine ( server_ip=localhost ) everything works. - post_zeew Nov.