helloThere helloThere - 1 year ago 117
Java Question

Arraylist through tcp in java?

How can I send an arraylist through tcp in Java?
I need to send an arraylist of integers, from client to server and vice verse.


Answer Source
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;

public class SerializeOverSocket {

    private static ExecutorService executorService =

    public static void main(String[] args) throws Exception {
        // Start a server to listen for a client
        executorService.submit(new Server());
        // Send an ArrayList from a client
        ArrayList<Integer> integers =
                    new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));
        Socket s = new Socket();
        s.connect(new InetSocketAddress("localhost", 1234));
        ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());

    static class Server implements Runnable {
        public void run() {
            try {
                ServerSocket server = new ServerSocket(1234);
                Socket clientSocket = server.accept();
                ObjectInputStream in =
                        new ObjectInputStream(clientSocket.getInputStream());
                Object o = in.readObject();
                System.out.println("Received this object on the server: " + o);
            } catch (IOException e) {
                // TODO: Write me
                throw new UnsupportedOperationException("Not written");
            } catch (ClassNotFoundException e) {
                // TODO: Write me
                throw new UnsupportedOperationException("Not written");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download