设为首页 收藏本站
查看: 536|回复: 0

[经验分享] 基于Tomcat的WebSocket(5月8日更新)

[复制链接]
累计签到:2 天
连续签到:1 天
发表于 2017-2-5 10:47:35 | 显示全部楼层 |阅读模式
  2014年2月更新: 此API为Tomcat私有,当时Java没有标准API,现在Java有标准API,JSR536,此API不建议使用,新的用法请参照: http://redstarofsleep.iteye.com/blog/1974620
  之前大概的看过WebSocket,当时Tomcat还不支持WebSocket,所以当时写了一篇基于Jetty的WebSocket实现,地址如下:
  http://redstarofsleep.iteye.com/blog/1307608
  现在Tomcat7.0.27发布了,从这个版本开始Tomcat就支持WebSocket了。
  Tomcat的WebSocket和Jetty的大致上差不多,大同小异,这里就简单的贴两个类吧(此例子未考虑多线程的情况):
  第一个类,这个和Jetty一样,需要一个Servlet来处理WebSocket请求:

package lhc.websocket;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
public class MyWebSocketServlet extends WebSocketServlet {
private static final long serialVersionUID = -7178893327801338294L;
@Override
protected StreamInbound createWebSocketInbound(String arg0) {
System.out.println("##########");
return new MyMessageInbound();
}
}
  这个Servlet继承自WebSocketServlet,实现createWebSocketInbound方法。该方法返回第二个类的实例。
  第二个类,处理每一次具体的WebSocket任务:

package lhc.websocket;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import lhc.init.InitServlet;
import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;
public class MyMessageInbound extends MessageInbound {
@Override
protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
// TODO Auto-generated method stub
}
@Override
protected void onTextMessage(CharBuffer msg) throws IOException {
for (MessageInbound messageInbound : InitServlet.getSocketList()) {
CharBuffer buffer = CharBuffer.wrap(msg);
WsOutbound outbound = messageInbound.getWsOutbound();
outbound.writeTextMessage(buffer);
outbound.flush();
}
}
@Override
protected void onClose(int status) {
InitServlet.getSocketList().remove(this);
super.onClose(status);
}
@Override
protected void onOpen(WsOutbound outbound) {
super.onOpen(outbound);
InitServlet.getSocketList().add(this);
}

}

  这个类继承自MessageInbound类,必须实现onBinaryMessage和onTextMessage方法。Jetty中只有一个onMessage方法,而Tomcat细化成了2个方法。
  还要一个初始化的Servlet

package lhc.init;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.catalina.websocket.MessageInbound;
public class InitServlet extends HttpServlet {
private static final long serialVersionUID = -3163557381361759907L;
private static List<MessageInbound> socketList;  
public void init(ServletConfig config) throws ServletException {  
InitServlet.socketList = new ArrayList<MessageInbound>();  
super.init(config);  
System.out.println("Server start============");  
}  
public static List<MessageInbound> getSocketList() {  
return InitServlet.socketList;  
}  
}
  最后,web.xml中进行一下Servlet的配置。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>wsoc</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>mywebsocket</servlet-name>
<servlet-class>lhc.websocket.MyWebSocketServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mywebsocket</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>initServlet</servlet-name>
<servlet-class>lhc.init.InitServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
</web-app>
  页面的话,就是标准的HTML5的websocket,这个和服务器是否是Tomcat或者Jetty是无关的:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index</title>
<script type="text/javascript">
var ws = null;
function startWebSocket() {
if ('WebSocket' in window)
ws = new WebSocket("ws://localhost:8080/wsoc/mywebsocket.do");
else if ('MozWebSocket' in window)
ws = new MozWebSocket("ws://localhost:8080/wsoc/mywebsocket.do");
else
alert("not support");

ws.onmessage = function(evt) {
alert(evt.data);
};
ws.onclose = function(evt) {
alert("close");
};
ws.onopen = function(evt) {
alert("open");
};
}
function sendMsg() {
ws.send(document.getElementById('writeMsg').value);
}
</script>
</head>
<body >
<input type="text" id="writeMsg"></input>
<input type="button" value="send" ></input>
</body>
</html>
   转载请注明出处

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-337719-1-1.html 上篇帖子: tomcat 远程调用 websphere remote session bean 一例 下篇帖子: 转 Tomcat内存溢出的三种情况及解决办法
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表