使用WebSocket实现图文直播功能
2016-07-15 17:06
731 查看
WebSocket,简单理解就是H5自带的一套Socket API,用它来实现客户端与服务端的长连接。
使用案例: 实现一个活动的实时报道,也就是图文直播功能
首先来看下项目的结构,很简单,就两个类
MyWebSocket.java
这个就是socket的服务端,功能方面只需添加相应的注解即可,注意类名上的注解@ServerEndpoint(“/websocket”),这个/websocket就好比是配置在web.xml中的servlet url一样。
H5客户端对应这个服务端实现信息的交互
LiveServlet.java
这个是用来统一入口的,即用户通过唯一路径http://localhost/websocket进入直播
服务端就这么简单的实现了下,具体根据自己的业务逻辑处理,再来看看客户端
交互基本就是这个样子了,案例清晰明了,代码也简单,可以快速对websocket上手
项目源码下载 (要收一分积分哦,搞点积分提升下逼格[笑])
使用案例: 实现一个活动的实时报道,也就是图文直播功能
首先来看下项目的结构,很简单,就两个类
MyWebSocket.java
这个就是socket的服务端,功能方面只需添加相应的注解即可,注意类名上的注解@ServerEndpoint(“/websocket”),这个/websocket就好比是配置在web.xml中的servlet url一样。
H5客户端对应这个服务端实现信息的交互
package websocket.server; import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; //该注解用来指定一个URI,客户端可以通过这个URI来连接到WebSocket。类似Servlet的注解mapping。无需在web.xml中配置。 @ServerEndpoint("/websocket") public class MyWebSocket { // 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 private static int onlineCount = 0; // concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识 private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>(); // 与某个客户端的连接会话,需要通过它来给客户端发送数据 private Session session; /** * 连接建立成功调用的方法 * * @param session * 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据 * @throws IOException */ @OnOpen public void onOpen(Session session) throws IOException { this.session = session; webSocketSet.add(this); // 加入set中 addOnlineCount(); // 在线数加1 System.out.println("有新连接加入!当前在线人数为" + getOnlineCount()); //模拟从数据库中取出历史信息 this.sendMessage("<img src='http://localhost/websocket/image/water.gif'>"); this.sendMessage("这是第一张现场图,散水.gif"); this.sendMessage("<hr />"); this.sendMessage("<img src='http://localhost/websocket/image/test.jpg'>"); this.sendMessage("这是第二张图哦....."); this.sendMessage("<br/>"); this.sendMessage("---------------------------以上是历史信息---------------------------<br/>"); } /** * 连接关闭调用的方法 */ @OnClose public void onClose() { webSocketSet.remove(this); // 从set中删除 subOnlineCount(); // 在线数减1 System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount()); } /** * 收到客户端消息后调用的方法 * * @param message * 客户端发送过来的消息 * @param session * 可选的参数 */ @OnMessage public void onMessage(String message, Session session) { System.out.println("来自客户端的消息:" + message); // 群发消息 for (MyWebSocket item : webSocketSet) { try { item.sendMessage("<img src='http://localhost/websocket/image/water.gif'>");//模拟上传的图片 item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); continue; } } } /** * 发生错误时调用 * * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { System.out.println("发生错误"); error.printStackTrace(); } /** * 发送信息给客户端 * * @param message * @throws IOException */ public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); // this.session.getAsyncRemote().sendText(message); } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { MyWebSocket.onlineCount++; } public static synchronized void subOnline 4000 Count() { MyWebSocket.onlineCount--; } }
LiveServlet.java
这个是用来统一入口的,即用户通过唯一路径http://localhost/websocket进入直播
package websocket.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LiveServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub super.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub String method = req.getParameter("method"); if ("tolive".equals(method)) { req.getRequestDispatcher("/WEB-INF/jsp/client.jsp").forward(req, resp); }else if("fabu".equals(method)){ //这里实现文件上传后返回图片url给客户端,客户端发送这个url给websocket服务端,此处应有代码...请脑补 } } }
服务端就这么简单的实现了下,具体根据自己的业务逻辑处理,再来看看客户端
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML> <html> <head> <base href="<%=basePath%>"> <title>Client webSocket</title> <script type="text/javascript" src="http://file.iqilu.com/custom/new/public/js/jquery-1.8.1.min.js"></script> <script> $(document).ready(function() { }); function load() { $(".content").hide(); } </script> <style type="text/css"> img { width: 100px; height: 100px } </style> </head> <body onload="load()"> <br /> <br /> <p class="tip" style="color: #fe1234">正在进入图文直播...</p> <div class="content"> <div id="message"></div> <p>快来发布你的现场图吧~</p> <br /> <br /> <form action="http://localhost/websocket/liveservlet?method=fabu" method="post"> <input type="file" value="请选择图片" /><button onclick="upLoadFile()">上传图片</button> <input id="comment" type="text" value="来段简短描述吧" /><br /> </form> <button onclick="send()">发布</button> <button onclick="closeWebSocket()">退出直播</button> </div> </body> <script type="text/javascript"> var websocket = null; //判断当前浏览器是否支持WebSocket if ('WebSocket' in window) { websocket = new WebSocket("ws://localhost/websocket/websocket"); } else { alert('Not support websocket') } //连接发生错误的回调方法 websocket.onerror = function() { setMessageInnerHTML("error"); }; //连接成功建立的回调方法 websocket.onopen = function(event) { $(".content").show(); $(".tip").text("2016XXXX在线峰会直播"); } //接收到消息的回调方法 websocket.onmessage = function(event) { setMessageInnerHTML(event.data); } //连接关闭的回调方法 websocket.onclose = function() { setMessageInnerHTML("close"); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function() { websocket.close(); } //将消息显示在网页上 function setMessageInnerHTML(innerHTML) { document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //关闭连接 function closeWebSocket() { websocket.close(); } //发送消息 function send() { var message = document.getElementById('comment').value; websocket.send(message); } </script> </html>
交互基本就是这个样子了,案例清晰明了,代码也简单,可以快速对websocket上手
项目源码下载 (要收一分积分哦,搞点积分提升下逼格[笑])
相关文章推荐
- 2015-2016网页设计趋势分析 Web Design of Trends
- Spring整合WebSocket应用示例(上)
- 详解java WebSocket的实现以及Spring WebSocket
- 浅析nodejs实现Websocket的数据接收与发送
- Spring整合websocket整合应用示例(下)
- 基于html5和nodejs相结合实现websocket即使通讯
- 基于node实现websocket协议
- Android中使用WebSocket实现群聊和消息推送功能(不使用WebView)
- php使用websocket示例详解
- php+html5基于websocket实现聊天室的方法
- Javascript WebSocket使用实例介绍(简明入门教程)
- 使用Java和WebSocket实现网页聊天室实例代码
- java中实现兼容ie6 7 8 9的spring4+websocket
- HTML5之WebSocket入门3 -通信模型socket.io
- Java后端Tomcat实现WebSocket实例教程
- 使用JavaWeb webSocket实现简易的点对点聊天功能实例代码
- Spring和Websocket相结合实现消息的推送
- java WebSocket的实现以及Spring WebSocket示例代码
- SpringMVC整合websocket实现消息推送及触发功能
- Python实现同时兼容老版和新版Socket协议的一个简单WebSocket服务器