利用webSocket使网页和服务器通信
Posted 小玄影123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用webSocket使网页和服务器通信相关的知识,希望对你有一定的参考价值。
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上就可以访问了,记得要先打开通道,输入文字就行
第一次写东西,如有错误还请指教,继续学习中。。。。
以上是关于利用webSocket使网页和服务器通信的主要内容,如果未能解决你的问题,请参考以下文章