1

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.

Thanxx

0

4 Answers 4

11
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;

public class SerializeOverSocket {

    private static ExecutorService executorService =
                    Executors.newSingleThreadExecutor();

    public static void main(String[] args) throws Exception {
        // Start a server to listen for a client
        executorService.submit(new Server());
        Thread.sleep(100);
        // 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());
        out.writeObject(integers);
        s.close();
    }

    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);
                clientSocket.close();
                server.close();
                executorService.shutdown();
            } catch (IOException e) {
                // TODO: Write me
                throw new UnsupportedOperationException("Not written");
            } catch (ClassNotFoundException e) {
                // TODO: Write me
                throw new UnsupportedOperationException("Not written");
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

8 Comments

oh you have him all the fish :) my answer only gives him the rod and a tells him how to fish)
Ha! Well, I suppose that's true. +1 for that.
It will of course save him a lot of time, but it is possible that he just copy-pastes it. @OP try understanding the example before using it.
Thanx allot guys. It will indeed save me allot of time, and i do appreciate that.
@helloThere: Like Bozho said, be sure you understand the code. There are some things in there that are only there because it's an example. You wouldn't ever really do them.
|
3

The simplest way would be:

  • serialize to byte[] (or directly write to the output stream as shown by Ryan)
  • open a socket
  • write the bytes in the client
  • receive the bytes on the server
  • deserialize the byte[] (or read from the stream as shown by Ryan)

To handle serialization use ObjectOutputStream and ObjectInputStream. You can also use commons-lang SerializationUtils which give you one-liners to serialize and deserialize.

1 Comment

I read your comment above, about the fish i mean :) But the thing is that as many times i have read streams and sockets I cant never seem to understand the completely :(
0

Look into serialization. Java's ArrayList object already implements the serializable interface, so you just have to learn how to use it.

http://www.java2s.com/Tutorial/Java/0140__Collections/ArrayListimplementstheemptySerializableinterface.htm

That example shows how to write an ArrayList to a file, but the same concept applys to sending it over sockets.

2 Comments

sorry i cant access the website :(
Sorry about that, something strange happened with my paste, here it is agian java2s.com/Tutorial/Java/0140__Collections/…
0

I know this is a very old question, but perhaps newer versions of the Java lang have make sending objects through TCP easier than in the past. And this is simpler than it seems. Checkout the following example:

Client side of your TCP connection:

//All the imports here
//...
public class Client {
    private ObjectInputStream in; //The input stream
    private ObjectOutputStream out; //The output stream
    private Socket socket; //The socket

    public Client(){
        //Initialize all the members for your
        //Client class here
    }

    //Using your sendData method create 
    //an array and send it through your 
    //output stream object
    public void sendData(int[] myIntegerArray) {
        try {
            //Note the out.writeObject
            //this means you'll be passing an object
            //to your server
            out.writeObject(myIntegerArray);
            out.flush();
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Server side of your TCP connection:

//All the imports here
//...
public class Server {
    private ObjectInputStream in; //The input stream
    private ObjectOutputStream out; //The output stream
    private ServerSocket serverSocket; //The serverSocket

    public Server(){
        //Initialize all the members for your
        //Server class here
    }

    //Using your getData method create 
    //the array from the serialized string
    //sent by the client
    public void getData() {
        try {
            //Do a cast to transform the object
            //into the actual object you need
            //which is an Integer array
            int[] data = (int[]) in.readObject();
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.