2011-07-15 33 views

回答

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

哦,你擁有他所有的魚:)我的回答只給他他的杆和一個告訴他如何釣魚) – Bozho

+0

哈!那麼,我想這是真的。 +1。 –

+0

這當然會爲他節省很多時間,但他可能只是複製粘貼它。 @OP在使用它之前嘗試理解示例。 – Bozho

0

查看序列化。 Java的ArrayList對象已經實現了可序列化的接口,所以你只需要學習如何使用它。

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

這個例子說明了如何寫一個ArrayList到一個文件,但相同的概念applys來發送它通過套接字。

+0

抱歉,我不能訪問該網站:( – helloThere

+0

對不起關於這一點,我的貼子發生了一些奇怪的事情,在這裏它是agian http://www.java2s.com/Tutorial/Java/0140__Collections/ArrayListimplementstheemptySeriali zableinterface.htm – xunil154

+0

非常有幫助thanx;) – helloThere

3

的最簡單的方法是:

  • 連載到byte[](或直接寫入到輸出流如圖所示由Ryan)
  • 打開套接字
  • 寫字節在客戶端
  • 接收服務器上的字節
  • 反序列化byte[](或從Ryan所示的流中讀取)

handle serialization使用ObjectOutputStreamObjectInputStream。您也可以使用commons-lang SerializationUtils,它們爲您提供單行序列化和反序列化。

+0

我讀過你的評論上面,關於我的意思是魚:)但事情是,我已經讀了多少次流和套接字我不能從來沒有完全理解:( – helloThere

0

我知道這是一個非常古老的問題,但也許更新版本的Java lang使通過TCP發送對象比過去更容易。這看起來比較簡單。結帳下面的例子:你的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); 
     } 
    } 

} 

服務器端:

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

}