socket 长连接+心跳

元气小坏坏 提交于 2020-08-13 04:59:33

由于长连接加心跳的机制,我们使用缓存技术将socket生成对象操作流(ObjectOutputStream)的方式,可以模拟出客户端获取数据流在进行操作,但是相应的ObjectOutputStream 和 ObjectInputStream方法需要屏蔽掉readStreamHeader和writeStreamHeader,(即重写)来防止Streamheader的检查。所以需要客户端在接收InputStream时,也需要用屏蔽掉readStreamHeader的ObjectInputStream来进行操作,发送时屏蔽掉ObjectOutputStream的writeStreamHeader。示例如下。

屏蔽的示例:

 继承ObjectInputStream: 

public class MyObjectInputStream extends ObjectInputStream  implements Serializable {

    private static final long serialVersionUID = 1L;

    public MyObjectInputStream() throws IOException {

        super();

    }

    public MyObjectInputStream(InputStream in) throws IOException {

        super(in);

    }

    protected void readStreamHeader() throws IOException {

        return;

    }

}

 继承ObjectOutputStream: 

public class MyObjectOutputStream  extends ObjectOutputStream implements Serializable{

    private static final long serialVersionUID = 1L;

    public MyObjectOutputStream(OutputStream out) throws IOException {

        super(out);

    }

    public MyObjectOutputStream() throws IOException {

        super();

    }

    public void writeStreamHeader() throws IOException{

        return;

    }

}

 

客户端示例:

接收返回数据包:

try {

                   InputStream in = socket.getInputStream();

                   if(in.available()>0){

                       MyObjectInputStream ois = new MyObjectInputStream(in);

                       String objStr = ois.readUTF();

                       System.out.println("接收:\t"+objStr);

                   }else{

                       Thread.sleep(10);

                   }

               } catch (Exception e) {

                   e.printStackTrace();

                   Client.this.stop();

               }

 

发送数据包:

    public void sendString(String obj) throws IOException {

        MyObjectOutputStream oos = new MyObjectOutputStream(socket.getOutputStream());

        oos.writeUTF(obj);

        System.out.println("发送:\t"+obj);

        oos.flush();

}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!