我想把Socket类的对象序列化后存储   
  请问如何实现啊?   
  我想到继承:   
    
  public   class   MySocket   extends   Socket   implements   Serializable{   
      public   MySocket()   {   
      }   
  }   
    
  在其他地方:   
  MySocket   client_socket   =   (MySocket)listen_socket.accept();   
  出现异常提示:java.lang.ClassCastException   
  请问怎么序列化Socket呢? 

解决方案 »

  1.   

    你这是类型转换错误 和序列化无关
    序列化和反序列化是这样的 import  java.io. * ;  class  tree  implements  java.io.Serializable   { 
         public  tree left; 
         public  tree right; 
         public   int  id; 
         public   int  level;      private   static   int  count  =   0 ;      public  tree( int  depth)   { 
            id  =  count ++ ; 
            level  =  depth; 
             if  (depth  >   0 )   { 
                left  =   new  tree(depth - 1 ); 
                right  =   new  tree(depth - 1 ); 
            }  
        }       public   void  print( int  levels)   { 
             for  ( int  i  =   0 ; i  <  level; i ++ ) 
                System.out.print( "    " ); 
            System.out.println( " node  "   +  id);          if  (level  <=  levels  &&  left  !=   null ) 
                left.print(levels);          if  (level  <=  levels  &&  right  !=   null ) 
                right.print(levels); 
        }  
         public   static   void  main (String argv[])   {          try    { 
                 /**/ /*  创建一个文件写入序列化树。  */  
                FileOutputStream ostream  =   new  FileOutputStream( " tree.tmp " ); 
                 /**/ /*  创建输出流  */  
                ObjectOutputStream p  =   new  ObjectOutputStream(ostream);              /**/ /*  创建一个二层的树。  */  
                tree base  =   new  tree( 2 );             p.writeObject(base);  //  将树写入流中。  
                 p.writeObject( " LiLy is 惠止南国 " );
                p.flush(); 
                ostream.close();     //  关闭文件。  
     
                  /**/ /*  打开文件并设置成从中读取对象。  */  
                FileInputStream istream  =   new  FileInputStream( " tree.tmp " ); 
                ObjectInputStream q  =   new  ObjectInputStream(istream);              /**/ /*  读取树对象,以及所有子树  */  
                tree new_tree  =  (tree)q.readObject();             new_tree.print( 2 );   //  打印出树形结构的最上面 2级  
                 String name  =  (String)q.readObject();
                System.out.println( " \n " + name);
            }   catch  (Exception ex)   { 
                ex.printStackTrace(); 
            }  
        }  
    }   
      

  2.   

    可以写一个类,实现Serializable   
      然后通过Socket传递这个类的对象   
      就可以实现串行化了