基于Tomcat的WebSocket(五月份8日更新)
基于Tomcat的WebSocket(5月8日更新)之前大概的看过WebSocket,当时Tomcat还不支持WebSocket,所以当时写了一
基于Tomcat的WebSocket(5月8日更新)
之前大概的看过WebSocket,当时Tomcat还不支持WebSocket,所以当时写了一篇基于Jetty的WebSocket实现,地址如下:
http://redstarofsleep.iteye.com/blog/1307608
?
现在Tomcat7.0.27发布了,从这个版本开始Tomcat就支持WebSocket了。
Tomcat的WebSocket和Jetty的大致上差不多,大同小异,这里就简单的贴两个类吧(此例子未考虑多线程的情况):
?
第一个类,这个和Jetty一样,需要一个Servlet来处理WebSocket请求:
<%@?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?onload="startWebSocket();">??<input?type="text"?id="writeMsg"></input>??<input?type="button"?value="send"?onclick="sendMsg()"></input>??</body>??</html>?