嘿,我们想通过 tomcat websockets 定期将缓冲图像发送到画布中,有点像直播。
服务器代码:
private static void broadcastImage(BufferedImage img) {
StreamInbound someClient;
byte[] arr = BufferedImageToByte(img);
ListIterator<StreamInbound> iter = clients.listIterator();
while (iter.hasNext()) {
someClient = (MessageInbound) iter.next();
try {
someClient.getWsOutbound().writeBinaryMessage(ByteBuffer.wrap(arr));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static byte[] BufferedImageToByte(BufferedImage img) {
byte[] imageInBytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
imageInBytes = baos.toByteArray();
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
return imageInBytes;
}
问题是如何将它打包到画布中。
客户代码:
ws = new WebSocket("ws://"+ location.host + "/carduinowebdroid/websocket");
ws.binaryType = "arraybuffer";
/** stuff **/
ws.onmessage = function(message){
if (message.data instanceof ArrayBuffer) {
streamHandleMessage(message);
}
}
function streamHandleMessage(message) {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
/** what now? **/
}
任何帮助是极大的赞赏!