JAVA SOCKET 序列化反序列化
以下是客户端序列化后将对象发送给服务端
public ResponseBean r(int b) { try { Socket socket = new Socket(Config.ServerIP,Config.ServerPort); RequestBean rb = new RequestBean(); rb.password = this.password; rb.ctrl = b; OutputStream outputStream = socket.getOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(rb); objectOutputStream.flush(); objectOutputStream.close(); //socket.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
以下是服务端接收到序列化之后进行反序列化
1 public void r(Socket s){ //进行管理的函数 2 try { 3 InputStream inputStream = s.getInputStream(); 4 5 6 ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); 7 try { 8 RequestBean rb =(RequestBean) objectInputStream.readObject(); 9 System.out.println(rb.password); 10 } catch (ClassNotFoundException e) { 11 // TODO Auto-generated catch block 12 System.out.println("err 收到客户端的请求不能发序列化到RequestBean"); 13 //e.printStackTrace(); 14 } 15 16 17 18 } catch (IOException e) { 19 // TODO Auto-generated catch block 20 e.printStackTrace(); 21 } 22 }
以下是序列化对象记得要实现Serializable接口,不然会出现unknown source这样的错误
package cn.fucihua.Model.Bean; import java.io.Serializable; public class RequestBean implements Serializable{ //序列化之后传给代理池服务的对象 public String password = ""; public int ctrl = 0; /* * 1 开启服务 * 2 关闭服务 * 3 重启服务 * 0 查询状态 * */ }
服务端客户端的类包名记得要一致