WebSocket protocol 是HTML5一種新的協議。它實現了浏覽器與服務器全雙工通信(full-duplex)。具體說明請查閱相關資料,下面我來演示一種簡單的頁面與服務器通信的簡單樣例。
新建個web工程(基於tomcat-7版本(6以下的版本未實現webSocket功能))
引入tomcat/lib目錄下的tomcat7-websocket.jar和websocket-api.jar添加到classpath中
新建WebSocketConfig.java如下
本次采用注解方式
import java.util.Set; import javax.websocket.Endpoint; import javax.websocket.server.ServerApplicationConfig; import javax.websocket.server.ServerEndpointConfig; public class WebSocketConfig implements ServerApplicationConfig{ @Override public Set<ServerEndpointConfig> getEndpointConfigs( Set<Class<? extends Endpoint>> scanned) { return null; } @Override public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) { //返回scanned return scanned; } }
編寫EchoSocket代碼
import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; @ServerEndpoint("/zqq/echo") public class EchoSocket { public EchoSocket() { super(); } @OnOpen public void open(Session session){ System.out.println("id " + session.getId()); } @OnMessage public void message(Session session,String msg){ System.out.println("sessionid " + session.getId() + " : " + msg); } }
此時編寫客戶端echo.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isELIgnored="false"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'open.jsp' starting page</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;
//websocket,協議開頭為ws var target = "ws://${pageContext.request.remoteHost}:8080${pageContext.request.contextPath}/zqq/echo"; function subOpen() { if ('WebSocket' in window) { ws = new WebSocket(target); } else if ('MozWebSocket' in window) { ws = new MozWebSocket(target); } else { alert('WebSocket is not supported by this browser.'); return; } ws.onmessage=function(event){ console.info(event.data); console.info(document.getElementById("h1").value); document.getElementById("h1").innerHTML+=event.data+" "; }; } function subSend(){ var text = document.getElementById("input").value; //alert(text); ws.send(text); document.getElementById("input").value=""; } </script> </head> <body> <button onclick="subOpen()">點擊開啟</button><br/> <input id="input"><br/> <button onclick="subSend()">發送</button> </body> </html>
此時將程序部署到tomcat上就可以訪問了,記得要先打開通道,輸入文字就行
第一次寫東西,如有錯誤還請指教,繼續學習中。。。。