前言

这几天有个小伙伴要实现http协议的服务器推的业务,于是就简单实现了下,且利用客户端模拟持续发送请求,模拟双向通信,当然只是一种简单的模型,如要应用于实际请慎重!

客户端代码:

package com.test.client;

import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpLongConnectionClient {
public static void main(String[] args) {
    try {

         URL url = new URL("http://localhost:8080/TestWeb/test.do");  
          ReqRunnable rr = new ReqRunnable(url);
            Thread reqThread = new Thread(rr);
            reqThread.start();

            InputStream in=url.openStream();  
            int n = -1;  
            byte[] b = new byte[1024];

            while((n=in.read(b))!=-1)  
            {  
                String s=new String(b,0,n);  
                System.out.println(s);      
            }  

    } catch (Exception e) {
        e.printStackTrace();
    }
}

static class ReqRunnable implements Runnable{
    URL url;
    ReqRunnable(URL url){
        this.url = url;
    }
    @Override
    public void run() {
        try {
            int count=0;
            while(true){
                //模拟新事件产生
                HttpURLConnection conn = (HttpURLConnection) this.url.openConnection();
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
                conn.setUseCaches(false);
                OutputStreamWriter out = new  OutputStreamWriter (conn.getOutputStream());
                String test = "data=yes"+count++;
                out.write(test);
                System.out.println("===>"+test);
                out.flush();                                         
                out.close();
                InputStream inputStream = conn.getInputStream();  
                Thread.sleep(3000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
}    

服务器端代码:

public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;


    public TestServlet() {
        super();
    }


protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    try{
        PrintWriter out = response.getWriter();
        int count = 0;
        while(true){
            System.out.println("read from client"+request.getParameter("data"));
            out.println("hello"+count);
            out.flush();
            Thread.sleep(1000);
            count++;
        }
    }catch(Exception e){
        e.printStackTrace();
    }

}

}

小结

简单实现http协议服务器推,感觉写得好恶心,纯属娱乐~ 后续研究更好的方案。

##文档信息