标签:
卤煮最近在做一个项目,需要用到服务器与页面进行通讯。
常见的ajax循环检测(轮询)对服务器压力较大,于是组长建议使用WebSocket技术,即长连接。
这里记录一下搭建WebSocket运行环境的心得体会,以飨大家。
运行环境: Windows System 7, Eclipse Mars 3.1, Tomcat 7.0.48/7.0.69, spring 4.0.2
最开始使用的是Tomcat7.0.48 搭配 servlet用。
需要建立两个类
分别继承WebSocketServlet 和 StreamInbound 两个类
public class WebSocketEnvironmental extends WebSocketServlet{ private static final long serialVersionUID = 1L; private final AtomicInteger connectionIds = new AtomicInteger(); @Override protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest request) { return new WebSocketMessage(connectionIds , request); } }
public class WebSocketMessage extends StreamInbound{ private HttpServletRequest request; private AtomicInteger connectionIds; public WebSocketMessage(AtomicInteger connectionIds, HttpServletRequest request) { this.connectionIds = connectionIds; this.request = request; } @Override protected void onTextData(Reader reader) throws IOException { char[] carr = new char[1024]; int length = reader.read(carr); onSend(String.copyValueOf(carr, 0, length)); } protected void onClose(int status){ System.out.println(String.format("websocket closing ......")); super.onClose(status); } protected void onOpen(WsOutbound outbound){ super.onOpen(outbound); System.out.println(String.format("webscoket opening ......")); } private void onSend(String message) throws IOException{ getWsOutbound().writeTextMessage(CharBuffer.wrap(message)); } @Override protected void onBinaryData(InputStream inStream) throws IOException { } }
并在web.xml里配置servlet启动服务
...... <!-- 配置WebSocketService运行环境 --> <servlet> <servlet-name>webscoket</servlet-name> <servlet-class>com.videtek.majorcase.websocket.WebSocketEnvironmental</servlet-class> </servlet> <servlet-mapping> <servlet-name>webscoket</servlet-name> <url-pattern>/webSocketServer</url-pattern> </servlet-mapping> .....
最后在页面上建立websocket连接,即可实现服务端与客户端(浏览器)
js代码以后再附上,网上也有很多类似的代码
关于Tomcat 和 Spring 整合 WebSocket 的心得体会 (一)
标签:
原文地址:http://www.cnblogs.com/xiaoxiangdezhuazi/p/5754010.html