用udp發送java對象
在一個java的socket連接中,用ObjectInputStream 和ObjectOutputStream可以很輕松的實現對Object的發送,但是如果沒有建立socket連接,如何用udp包來發送Object對象呢? |
|
public void SendInfo(int code, Object obj){ ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try{ oos = new ObjectOutputStream(baos); oos.writeInt(code); oos.writeObject(obj); oos.flush(); byte arr[] = baos.toByteArray(); if(arr == null)return; SendDataToClient(arr); if(baos != null)baos.close(); if(oos != null)oos.close(); }catch(Exception e){ FuncForServer.WriteErrMsg( "Exception in Sending data to server.", e); } } 其中SendDataToClient(arr);就不用我說了吧 然后接受方接受到了這個包后呢? 接收到的數組組成對象: ByteArrayInputStream bais = new ByteArrayInputStream(dataq); ObjectInputStream ois = null; byte arr[] = null; ois = new ObjectInputStream(bais); Object obj = ois.readObject(); obj就到了,呵呵! |
posted on 2007-08-05 08:29 lqx 閱讀(916) 評論(0) 編輯 收藏 所屬分類: network