Re: [問題] 用socket傳object

看板java作者 (偶爾想擺爛一下)時間16年前 (2009/12/03 20:26), 編輯推噓1(102)
留言3則, 2人參與, 最新討論串1/1
※ 引述《InitialShuk (Shuk)》之銘言: : server先執行 在client : server: : public class s { : public static void main(String[] args) { : try { : ServerSocket _port=new ServerSocket(9876); : Socket _sock=_port.accept(); : ObjectInputStream _ois=new ObjectInputStream(_sock.getInputStream()); : System.out.println(_ois.readUTF()); : Object _one=_ois.readObject(); : System.out.println("e"); : person _per=(person) _one; : System.out.println(_per.getID()); : } catch (Exception e) {e.printStackTrace();} : } : public class person implements Serializable{/*跟client的一起貼在下面*/} : } : client: : public class c implements Serializable{ <===註一 : public static void main(String[] args) { : new c().go();} : public void go(){ : try { : Socket _sock=new Socket("127.0.0.1",9876); : ObjectOutputStream _oos=new ObjectOutputStream(_sock.getOutputStream()); : person _per=new person("111","222","333","444"); : _oos.writeUTF("123"); : _oos.flush(); : _oos.writeObject(_per); : _oos.flush(); : } catch (IOException e) {e.printStackTrace();} : } : public class person implements Serializable{/*跟server的一起貼在下面*/} : } : 各自有相同的class :person (getter setter省略) : public class person implements Serializable{ : private static final long serialVersionUID = 1L; : public String ID; : public String name; : public String PN; : public String Email; : public person(String _temp1,String _temp2,String _temp3,String _temp4){ : this.ID=_temp1; : this.name=_temp2; : this.PN=_temp3; : this.Email=_temp4; : } : } : ----------------------- Server site 的 s.person 與 client site 的 c.person 是兩個不同的 class。 你不能夠讓 c.person object 做 serialization 後傳到 server site 直接變成 s.person object。 你的程式碼中還牽涉到 non-static inner class 的一些細節,導致情況變的複雜 到你目前沒有辦法 handle。 我建議你寫一個 top level class: Person 編譯好產出的 Person.class 部署到 server 與 client 兩方(不要 server/client 各寫一份 Person.java)。 然後按照類似你原來的流程去做物件的傳輸。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.173.131.1

12/03 20:27, , 1F
了解...冏
12/03 20:27, 1F

12/03 20:28, , 2F
class s/class c 都不需要 implements Serializable.
12/03 20:28, 2F

12/03 20:30, , 3F
非常感謝<(_ _)> 盲點真的讓人冏
12/03 20:30, 3F
文章代碼(AID): #1B5wvdNC (java)