开发者

Arraylist through tcp in java?

How can I send an arrayli开发者_如何转开发st through tcp in Java? I need to send an arraylist of integers, from client to server and vice verse.

Thanxx


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");
            }
        }
    }
}


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.


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.


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);
        }
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜