Server-Sent Events的Java简单实现

Server-Sent Events (SSE)是一种基于HTTP协议的单向通讯技术,只能服务器向客户端发送消息,如果客户端需要向服务器发送消息,则需要一个新的 HTTP 请求。SSE的实现方法可能参考阮一锋老师的文章。
在Java中,并没有像HTML5中SSE的封装实现,但我们可以模拟一个,以下为Java与Node.js服务器后台通讯的实现:

import java.io.*;
import java.net.*;

public class Sse {

    public Sse() {
        try {
            URL url = new URL("http://localhost:3400");
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setRequestProperty("Connection", "Keep-Alive");
            urlConnection.setRequestProperty("Charset", "UTF-8");
            urlConnection.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");
            this.output(urlConnection);
            InputStream is = new BufferedInputStream(urlConnection.getInputStream());
            this.readStream(is);
        } catch(Exception e) {
            System.out.println("Error:" + e.getMessage());
        }
    }
    
    public void output(HttpURLConnection conn) {
        String data = "HelloNode SSE.";
        try {
            byte[] dataBytes = data.getBytes();
            conn.setRequestProperty("Content-Length", String.valueOf(dataBytes.length));
            OutputStream os = conn.getOutputStream();
            os.write(dataBytes);
            os.flush();
            os.close();
        } catch(Exception e) {}
    }
    
    public void readStream(InputStream is) {
        BufferedReader reader = null;
        StringBuffer sb = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(is));
            String line = "";
            while((line = reader.readLine()) != null) {
                this.parseMessage(line);
            }
            reader.close();
        } catch(Exception e) {
            System.out.println("Error:" + e.getMessage());
        }
    }
    
    public void parseMessage(String msg) {
        //这里可以写接收消息后的逻辑
    }

    public static void main(String[] args) {
        new Sse();
    }
}

而node.js服务器端的代码则如下:

var http = require("http");

var server = http.createServer(function(req, res) {
    let chunks = [], len = 0;
    req.on("data", chunk => {
        chunks.push(chunk);
        len += chunk.length;
    }).on("end", () => {
        let buf = Buffer.concat(chunks, len);
        console.log("PostData:", buf.toString());
    });
    setInterval(function() {
        //这里可以根据用户请求的操作进行数据处理及返回
        res.write(Date.now() + "\r\n");
    }, 3000);
});

server.listen(3400);

以上为简单实现, 其中省略了服务器端的error捕获以及数据处理及返回的操作, 希望能对正在学习相关技术的人有一点点用处。

你可能感兴趣的:(Server-Sent Events的Java简单实现)