让jslinux可以实现两个浏览器数据互通。
效果图
原理:
jslinux已经实现了/dev/clipboard与浏览器的textarea的联通,
利用datachannel把两个浏览器的textarea交互,实现jslinux之间的数据交互
增加room概念,进入同一个room的两个页面才可以互相通信
要求tomcat7.0.62
java代码,java的websocket使给datachannel建立连接.
package com.hao; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.catalina.websocket.MessageInbound; import org.apache.catalina.websocket.StreamInbound; import org.apache.catalina.websocket.WebSocketServlet; import org.apache.catalina.websocket.WsOutbound; public class RoomWebSocketServlet extends WebSocketServlet { public static Mapslist = new HashMap (); protected StreamInbound createWebSocketInbound(String subProtocol, HttpServletRequest request) { System.out.println("room:"+request.getParameter("r")); String arg="0"; if(null!=request.getParameter("r")){ arg=request.getParameter("r"); } return new MyMessageInbound(arg); } public int getUserCount() { return slist.size(); } private class MyMessageInbound extends MessageInbound { WsOutbound myoutbound; String mykey; String room; public MyMessageInbound(String room){ this.room=room; } @Override public void onOpen(WsOutbound outbound) { try { System.out.println("websocket Client open."); this.myoutbound = outbound; mykey = "" + System.currentTimeMillis(); slist.put(room+"::"+mykey, this); System.out.println("slist size:" + slist.size()); } catch (Exception e) { e.printStackTrace(); } } @Override public void onClose(int status) { System.out.println("websocket Close."+mykey); slist.remove(mykey); } @Override protected void onTextMessage(CharBuffer message) throws IOException { System.out.println("onTextMessage-------->"); for (Map.Entry entry : slist.entrySet()) { String socketroom=entry.getKey().split("::")[0]; String socketkey=entry.getKey().split("::")[1]; if(this.room.equals(socketroom)&&!this.mykey.equals(socketkey)){//向room相同但是不是当前websocket发送消息 System.out.println("-------->" + message.toString()); System.out.println("--->socketroom:"+socketroom+",socketkey:"+socketkey); MyMessageInbound mmib = (MyMessageInbound) entry.getValue(); CharBuffer buffer = CharBuffer.wrap(message); mmib.myoutbound.writeTextMessage(buffer); mmib.myoutbound.flush(); } } } @Override protected void onBinaryMessage(ByteBuffer arg0) throws IOException { } } }
web.xml中:
配置websocket的servlet
room com.hao.RoomWebSocketServlet room /hao/room
jslinux中的index修改
加入datachannel和