Tomcat7 配置 WebSocket

作者: icanflylzx2012
发布时间:2015-07-13 11:07:10

    这是本人第一次写技术性的博客,写的好与不好还请各位多多包含。哈哈~
    由于项目的要求需要使用WebSocket,公司的服务器是用C++写的,而我之前是名Java程序员,所以处于好奇变用Tomcat7配置实现了WebSocket的服务端。之前也查阅了很多资料,Tomcat7早先的版本提供了自己的WebSocket API,实现方式是继承WebSocketServlet,但是随着JavaEE 7标准的颁布,该方式不建议使用,好下面我们来看一下实现了JSR-356标准的WebSocket实现。
    我开始之前我现说明一下,我的开发工具使用的是MyEclipse10,Tomcat版本是7.0.57,Okay闲言少叙!

    首先新建一个Web Project,项目名my-websocket。

    

    然后接下来创建Tomcat7的Server lib,点击MyEclipse工具条[file]-[NEW]-[Other…]后弹出Select a wizard菜单。在Wizards:输入框输入”Server”选择Server并Next。

    

    之后出现众服务器列表,我们选择Tomcat v7.0 Server并点击Finish。此时出现Servers项目。

    

    好的我们继续,接下来在项目my-websocket中添加Server Runtime,选择项目my-websocket右键菜单[Build Path]-[Add Libraries…],在Add Libarary列表中选择WTP Server Runtime(MyEclipse incompatible)

    

    点击Next进入下一步,我们会看到之前建立的Tomcat 7 Server Library迅速选择Finish。

    

    好了WebSocket的所需的包就此导入完成,下面就可以编写代码了。新建Endpoint类文件MyServerEndpoint.java。

    

package com.websocket.endpoint;  import java.io.IOException;  import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint;   @ServerEndpoint(value = "/websocket/{user}") public class MyServerEndpoint { 	private Session session; 	 	@OnOpen 	public void open(Session session, @PathParam(value="user")String user) { 		this.session = session; 		System.out.println("->open : " + session.getId()); 	} 	 	@OnMessage 	public void inMessage(String message) throws IOException { 		System.out.println("->onMessage : " + this.session.getId()); 		this.session.getBasicRemote().sendText(message); 	} 	 	@OnClose 	public void end() { 		System.out.println("->close : " + this.session.getId()); 	} }
    客户端index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> 	<head> 		<base href="<%=basePath%>"> 		 		<title>WebSocket</title> 		<meta http-equiv="pragma" content="no-cache"> 		<meta http-equiv="cache-control" content="no-cache"> 		<meta http-equiv="expires" content="0">		 		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 		<meta http-equiv="description" content="This is my page"> 		<!-- 		<link rel="stylesheet" type="text/css" href="styles.css"> 		--> 		<script type="text/javascript">  			var ws; 			var url = "ws://" + window.location.host + "/mws/websocket/{user}"; 			var result;  			function initWebSocket() { 				result = document.getElementById("result"); 				if("WebSocket" in window) { 					ws = new WebSocket(url); 				}else if("MozWebSocket" in window) { 					ws = new MozWebSocket(url); 				}else { 					result.innerHTML = "No support WebSocket !<br>"; 				}  				ws.onopen = function() { 					result.innerHTML = "..# onopen" + "<br>"; 					ws.send("Hello WebSocket !"); 				}; 				ws.onmessage = function(event) { 					result.innerHTML += "..# onmessage : " + event.data + "<br>"; 				}; 				ws.onclose = function(event) { 					result.innerHTML += "..# onclose" + "<br>"; 				}; 			}  			function send() { 				ws.send(document.getElementById("msg").value); 			} 		</script> 	</head> 	 	<body onload="initWebSocket();"> 		<h1>WEBSOCKET</h1> 		<hr> 		<div id="result"></div> 		<textarea rows="5" cols="20" id="msg"></textarea> 		<br> 		<button onclick="send()">send</button> 	</body> </html>
    OK!部署Tomcat运行!输入地址http://localhost:8080/mws/

    

    注意:
    在Tomcat启动后,访问index.jsp出现500错误:

    

    解决方法:
    修改Tomcat的conf目录下的context.xml文件添加如下

<Context>      <!-- Default set of monitored resources -->     <WatchedResource>WEB-INF/web.xml</WatchedResource>      <!-- Uncomment this to disable session persistence across Tomcat restarts -->     <!--     <Manager pathname="" />     -->      <!-- Uncomment this to enable Comet connection tacking (provides events          on session expiration as well as webapp lifecycle) -->     <!--     <Valve className="org.Apache.catalina.valves.CometConnectionManagerValve" />     -->      <!-- 添加 -->     <Loader delegate="true"> </Context>

版权声明:本文为博主原创文章,未经博主允许不得转载。

标签: Tomcat Web WebSocket
来源:http://blog.csdn.net/icanflylzx2012/article/details/41451179

推荐: