Arraylist через TCP в Java? - PullRequest
       9

Arraylist через TCP в Java?

1 голос
/ 15 июля 2011

Как я могу отправить массив через tcp в Java?Мне нужно отправить массив целых чисел от клиента к серверу и наоборот.

Thanxx

Ответы [ 4 ]

11 голосов
/ 16 июля 2011
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");
            }
        }
    }
}
3 голосов
/ 16 июля 2011

Самый простой способ:

  • сериализировать в byte[] (или напрямую записать в выходной поток, как показано Райаном)
  • открыть сокет
  • записать байты в клиенте
  • получить байты на сервере
  • десериализировать byte[] (или прочитать из потока, как показано Райаном)

Для обработки сериализации используйте ObjectOutputStream и ObjectInputStream.Вы также можете использовать commons-lang SerializationUtils, который дает вам однострочники для сериализации и десериализации.

0 голосов
/ 24 июля 2016

Я знаю, что это очень старый вопрос, но, возможно, более новые версии языка Java сделали отправку объектов через TCP проще, чем в прошлом. И это проще, чем кажется. Оформить заказ на следующем примере:

Клиентская часть вашего TCP-соединения:

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

}

Серверная часть вашего TCP-соединения:

//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 голосов
/ 16 июля 2011

Посмотрите на сериализацию.Java-объект ArrayList уже реализует сериализуемый интерфейс, поэтому вам просто нужно научиться его использовать.

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

В этом примере показано, как записать ArrayList в файл, но тот жеКонцепция распространяется на отправку через сокеты.

...