socket系列(二)——Javaee实现实时通信
来源:互联网 发布:ubuntu输入法 编辑:程序博客网 时间:2024/06/05 18:55
实现
java自带javaee-api7.0实现
环境要求
Tomcat7.0以上支持(最好tomcat8.0以上)
Ie7,8,9不支持,可以有sockeJS代替
Jar包:javaee-api-7.0.jar
项目结构
Java代码
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; @ServerEndpoint(value = "/websocket")public classPushSocket { // 连接人数 private static int count; private staticCopyOnWriteArraySet<PushSocket> set = new CopyOnWriteArraySet<>(); // 服务端与客户端的通话 private Session session; @OnOpen public void onOpen(Session session) { this.session = session; set.add(this); addOnlineCount(); System.out.println("服务器在线人数:" + getOnlineCount()); } @OnClose public void onClose(Session session) { set.remove(this); subOnlineCount(); System.out.println("服务器在线人数:" + getOnlineCount()); } @OnMessage public void onMessage(String message, Session session) { System.out.println("来自客户端的消息:" + message); // 群发消息 for (PushSocket socket : set) { try { System.out.println(socket.hashCode()); socket.sendMsg(message); }catch(IOException e) { e.printStackTrace(); continue; } } } @OnError public void onError(Session session, Throwable error) { System.out.println("发生错误"); error.printStackTrace(); } /** * 某个连接发送消息 * @param msg */ public void sendMsg(String msg) throws IOException { this.session.getBasicRemote().sendText(msg); } public static int getOnlineCount() { return count; } public static void addOnlineCount() { count++; } public static void subOnlineCount() { count--; }}
Jsp代码
<%@ page language="java"contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>socket</title> <script type="text/javascript" src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> welcome<br /> <input id="text" type="text"/> <button onclick="sendMsg()">sendMsg</button> <hr/> <button onclick="closeWebSocket()">close WebSocketconnection</button> <hr/> <div id="message"></div> </body> <script type="text/javascript"> var websocket = null; //判断浏览器是否支持websocket if('WebSocket' in window) { websocket= newWebSocket("ws://localhost:8080/study_push/websocket"); }else{ $("#message").html("该浏览器不支持实时通信功能"); } websocket.onopen= function() { console.log("websocket连接成功"); } websocket.onclose= function() { console.log("websocket连接关闭"); } websocket.onmessage= function(event) { console.log("接收消息"); console.log(event); printMsg(event.data); } //打印消息 function printMsg(msg) { $("#message").append(msg+ "<br/>"); } function sendMsg() { var msg = $("#text").val(); websocket.send(msg); } function closeWebSocket(){ websocket.close(); } </script></html>
Web.xml配置
<?xml version="1.0"encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>study_push</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
运行
打开” http://localhost:8080/study_push/IMpage.jsp”,实现情况
总结
Javaee-api对于websocket的处理十分轻便,好用便捷。
Java代码:
"@ServerEndpoint(value ="/websocket")":tomcat就会默认把该标签的类当作一个websocket,value就是连接地址。
"@OnOpen":当有新的连接时执行方法,这里执行的是给session赋值,添加该连接对象,增加连接数量,打印连接信息。
"@OnClose":当有连接关闭时执行方法,这里执行的是移除连接对象和打印信息操作。
"@OnMessage":当有新消息传后台时执行方法,这里执行的是给所有连接对象发送该请求。
"@OnError":当有连接错误时执行方法。
每当有新的客户端连接时,都会创建一个新的PushSocket对象,所以这里用CopyOnWriteArraySet<PushSocket>set来存放所有的连接对象。
Js代码:
"websocket = new WebSocket()":连接服务器websocket,参数就是服务器websocket地址
"websocket.onopen":连接后执行。
"websocket.onclose":关闭执行。
"websocket.onmessage":服务器发送消息。
ie7、8、9不支持websocket,可以使用socketJS替代
- socket系列(二)——Javaee实现实时通信
- socket系列(三)——Spring-socket实时通信、推送
- Socket层实现系列 — bind()的实现(二)
- Socket层实现系列 — accept()的实现(二)
- JAVA系列课程讲座二:使用Socket通信实现简单聊天通信程序(UDP方式)
- Socket通信(二)-- 多线程服务器实现
- socket简单实现实时通信案例
- 【Java Socket】入门系列 3.2.编程实现基于 TCP 的 Socket 通信 — 服务器端和客户端
- 通过WebRTC实现实时视频通信(二)
- android实现Socket通信二
- IOS系列——socket通信
- JavaEE系列——第一章JavaEE概述
- 【Java Socket】入门系列 3.3.通过 Socket 实现 TCP 编程 — 使用多线程实现多客户端通信
- Socket通信实例(二)——单线程实例
- java Socket通信——TCP协议(二)
- socket系列(一)——socket实现推送
- 服务器开发—Socket通信实例(二)
- JavaEE知识整理系列(二)EJB
- highlight 动态添加代码,样式失效
- 算法提高 题目 3 函数求值
- spring MVC
- Linux_正则表达式(1.基础正则表达式)
- 英语阅读之二
- socket系列(二)——Javaee实现实时通信
- LeetCode 171. Excel Sheet Column Number (字符串、进制转换)
- 关于block循环引用的问题
- 面试HTTP问题总结
- linux:修改服务器时间跟当前时间一致的命令
- GUI键盘事件
- sql函数
- 在Servlet中获取Web路径和文件真实路径
- ZZULIOJ 1875 蛤玮的财宝【最大费用流】