2014-12-13 1 views
0

Java에서 UDP 서버에서 UDP 클라이언트로 벡터 객체를 보내려고합니다.Java에서 UDP over conection을 보내는 방법

문자열을 직렬화 한 후 개체로 보내고 받고 있지만 벡터를 보내거나받을 수 없습니다. 아래는 서버 ide 코드입니다.

public class UDPReceive { 


    public UDPReceive() throws IOException { 
    try { 

     int port = Integer.parseInt("1233"); 

     int allReceived=0; 
     String[] custData=new String[3]; 

     DatagramSocket dsocket = new DatagramSocket(port); 

     byte[] buffer = new byte[2048]; 
     for(;;) { 
     DatagramPacket packet = new DatagramPacket(buffer, buffer.length); 

     dsocket.receive(packet); 

     String msg = new String(buffer, 0, packet.getLength()); 
     String msg2 = new String(packet.getData()); 
     custData[allReceived]=msg; 
     allReceived++; 
     if(allReceived == 3){ 
      System.out.println("All Data Received"); 
      for(int i=0;i<3;i++){ 
       System.out.println(custData[i]); 
      } 
      Vector rawData=getTransactions(custData[0],custData[1],custData[2]); 
      System.out.println("Vectot size "+ rawData.size()); 
      byte[] sendData = new byte[1024]; 
      sendData=(object[])rawData.toArray(); 
      allReceived=0; 
     }/*if ends here */ 
     } 
    } 
    catch (Exception e) { 
     System.err.println(e); 
    } 
    } 

여기서 "rawData"변수를 클라이언트에 보내고 받아서 클라이언트 측의 벡터로 변환하고 싶습니다. 바이트 []도 사용했지만 작동하지 않았습니다.

답변

0

Vector를 ObjectOutputStream으로 serialize하고 ObjectInputStream을 사용하여 원본 Vector를 가져 오는 것이 좋습니다.

public static byte[] objectToBytes(Object o) throws IOException { 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    ObjectOutputStream oos = new ObjectOutputStream(baos); 
    oos.writeObject(o); 
    oos.close(); 
    return baos.toByteArray(); 
} 

반대하는

public static <T> T bytesToObject(byte[] bytes) throws IOException, ClassNotFoundException { 
    return (T) new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject(); 
} 
관련 문제