java 实现websocket的两种方式
简单说明
1.两种方式,一种使用tomcat的websocket实现,一种使用spring的websocket
2.tomcat的方式需要tomcat 7.x,JEE7的支持。
3.spring与websocket整合需要spring 4.x,并且使用了socketjs,对不支持websocket的浏览器可以模拟websocket使用
方式一:tomcat
使用这种方式无需别的任何配置,只需服务端一个处理类,
服务器端代码
- package com.Socket;
- import java.io.IOException;
- import java.util.Map;
- import java.util.concurrent.ConcurrentHashMap;
- import javax.websocket.*;
- import javax.websocket.server.PathParam;
- import javax.websocket.server.ServerEndpoint;
- import net.sf.json.JSONObject;
- @ServerEndpoint("/websocket/{username}")
- public class WebSocket {
- private static int onlineCount = 0;
- private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
- private Session session;
- private String username;
- @OnOpen
- public void onOpen(@PathParam("username") String username, Session session) throws IOException {
- this.username = username;
- this.session = session;
- addOnlineCount();
- clients.put(username, this);
- System.out.println("已连接");
- }
- @OnClose
- public void onClose() throws IOException {
- clients.remove(username);
- subOnlineCount();
- }
- @OnMessage
- public void onMessage(String message) throws IOException {
- JSONObject jsonTo = JSONObject.fromObject(message);
- if (!jsonTo.get("To").equals("All")){
- sendMessageTo("给一个人", jsonTo.get("To").toString());
- }else{
- sendMessageAll("给所有人");
- }
- }
- @OnError
- public void onError(Session session, Throwable error) {
- error.printStackTrace();
- }
- public void sendMessageTo(String message, String To) throws IOException {
- // session.getBasicRemote().sendText(message);
- //session.getAsyncRemote().sendText(message);
- for (WebSocket item : clients.values()) {
- if (item.username.equals(To) )
- item.session.getAsyncRemote().sendText(message);
- }
- }
- public void sendMessageAll(String message) throws IOException {
- for (WebSocket item : clients.values()) {
- item.session.getAsyncRemote().sendText(message);
- }
- }
- public static synchronized int getOnlineCount() {
- return onlineCount;
- }
- public static synchronized void addOnlineCount() {
- WebSocket.onlineCount++;
- }
- public static synchronized void subOnlineCount() {
- WebSocket.onlineCount--;
- }
- public static synchronized Map<String, WebSocket> getClients() {
- return clients;
- }
- }
客户端js
- var websocket = null;
- var username = localStorage.getItem("name");
- //判断当前浏览器是否支持WebSocket
- if ('WebSocket' in window) {
- websocket = new WebSocket("ws://" + document.location.host + "/WebChat/websocket/" + username + "/"+ _img);
- } else {
- alert('当前浏览器 Not support websocket')
- }
- //连接发生错误的回调方法
- websocket.onerror = function() {
- setMessageInnerHTML("WebSocket连接发生错误");
- };
- //连接成功建立的回调方法
- websocket.onopen = function() {
- setMessageInnerHTML("WebSocket连接成功");
- }
- //接收到消息的回调方法
- websocket.onmessage = function(event) {
- setMessageInnerHTML(event.data);
- }
- //连接关闭的回调方法
- websocket.onclose = function() {
- setMessageInnerHTML("WebSocket连接关闭");
- }
- //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
- window.onbeforeunload = function() {
- closeWebSocket();
- }
- //关闭WebSocket连接
- function closeWebSocket() {
- websocket.close();
- }
发送消息只需要使用websocket.send("发送消息"),就可以触发服务端的onMessage()方法,当连接时,触发服务器端onOpen()方法,此时也可以调用发送消息的方法去发送消息。关闭websocket时,触发服务器端onclose()方法,此时也可以发送消息,但是不能发送给自己,因为自己的已经关闭了连接,但是可以发送给其他人。
方法二:spring整合
此方式基于spring mvc框架,相关配置可以看我的相关博客文章
WebSocketConfig.java
这个类是配置类,所以需要在spring mvc配置文件中加入对这个类的扫描,第一个addHandler是对正常连接的配置,第二个是如果浏览器不支持websocket,使用socketjs模拟websocket的连接。
- package com.websocket;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.socket.config.annotation.EnableWebSocket;
- import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
- import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
- import org.springframework.web.socket.handler.TextWebSocketHandler;
- @Configuration
- @EnableWebSocket
- public class WebSocketConfig implements WebSocketConfigurer {
- @Override
- public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
- registry.addHandler(chatMessageHandler(),"/webSocketServer").addInterceptors(new ChatHandshakeInterceptor());
- registry.addHandler(chatMessageHandler(), "/sockjs/webSocketServer").addInterceptors(new ChatHandshakeInterceptor()).withSockJS();
- }
- @Bean
- public TextWebSocketHandler chatMessageHandler(){
- return new ChatMessageHandler();
- }
- }
ChatHandshakeInterceptor.java
这个类的作用就是在连接成功前和成功后增加一些额外的功能,Constants.java类是一个工具类,两个常量。
- package com.websocket;
- import java.util.Map;
- import org.apache.shiro.SecurityUtils;
- import org.springframework.http.server.ServerHttpRequest;
- import org.springframework.http.server.ServerHttpResponse;
- import org.springframework.web.socket.WebSocketHandler;
- import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
- public class ChatHandshakeInterceptor extends HttpSessionHandshakeInterceptor {
- @Override
- public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
- Map<String, Object> attributes) throws Exception {
- System.out.println("Before Handshake");
- /*
- * if (request instanceof ServletServerHttpRequest) {
- * ServletServerHttpRequest servletRequest = (ServletServerHttpRequest)
- * request; HttpSession session =
- * servletRequest.getServletRequest().getSession(false); if (session !=
- * null) { //使用userName区分WebSocketHandler,以便定向发送消息 String userName =
- * (String) session.getAttribute(Constants.SESSION_USERNAME); if
- * (userName==null) { userName="default-system"; }
- * attributes.put(Constants.WEBSOCKET_USERNAME,userName);
- *
- * } }
- */
- //使用userName区分WebSocketHandler,以便定向发送消息(使用shiro获取session,或是使用上面的方式)
- String userName = (String) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USERNAME);
- if (userName == null) {
- userName = "default-system";
- }
- attributes.put(Constants.WEBSOCKET_USERNAME, userName);
- return super.beforeHandshake(request, response, wsHandler, attributes);
- }
- @Override
- public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
- Exception ex) {
- System.out.println("After Handshake");
- super.afterHandshake(request, response, wsHandler, ex);
- }
- }
ChatMessageHandler.java
这个类是对消息的一些处理,比如是发给一个人,还是发给所有人,并且前端连接时触发的一些动作
- package com.websocket;
- import java.io.IOException;
- import java.util.ArrayList;
- import org.apache.log4j.Logger;
- import org.springframework.web.socket.CloseStatus;
- import org.springframework.web.socket.TextMessage;
- import org.springframework.web.socket.WebSocketSession;
- import org.springframework.web.socket.handler.TextWebSocketHandler;
- public class ChatMessageHandler extends TextWebSocketHandler {
- private static final ArrayList<WebSocketSession> users;// 这个会出现性能问题,最好用Map来存储,key用userid
- private static Logger logger = Logger.getLogger(ChatMessageHandler.class);
- static {
- users = new ArrayList<WebSocketSession>();
- }
- /**
- * 连接成功时候,会触发UI上onopen方法
- */
- @Override
- public void afterConnectionEstablished(WebSocketSession session) throws Exception {
- System.out.println("connect to the websocket success......");
- users.add(session);
- // 这块会实现自己业务,比如,当用户登录后,会把离线消息推送给用户
- // TextMessage returnMessage = new TextMessage("你将收到的离线");
- // session.sendMessage(returnMessage);
- }
- /**
- * 在UI在用js调用websocket.send()时候,会调用该方法
- */
- @Override
- protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
- sendMessageToUsers(message);
- //super.handleTextMessage(session, message);
- }
- /**
- * 给某个用户发送消息
- *
- * @param userName
- * @param message
- */
- public void sendMessageToUser(String userName, TextMessage message) {
- for (WebSocketSession user : users) {
- if (user.getAttributes().get(Constants.WEBSOCKET_USERNAME).equals(userName)) {
- try {
- if (user.isOpen()) {
- user.sendMessage(message);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- break;
- }
- }
- }
- /**
- * 给所有在线用户发送消息
- *
- * @param message
- */
- public void sendMessageToUsers(TextMessage message) {
- for (WebSocketSession user : users) {
- try {
- if (user.isOpen()) {
- user.sendMessage(message);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- @Override
- public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
- if (session.isOpen()) {
- session.close();
- }
- logger.debug("websocket connection closed......");
- users.remove(session);
- }
- @Override
- public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
- logger.debug("websocket connection closed......");
- users.remove(session);
- }
- @Override
- public boolean supportsPartialMessages() {
- return false;
- }
- }
spring-mvc.xml
正常的配置文件,同时需要增加对WebSocketConfig.java类的扫描,并且增加
- xmlns:websocket="http://www.springframework.org/schema/websocket"
- http://www.springframework.org/schema/websocket
- <a target="_blank" href="http://www.springframework.org/schema/websocket/spring-websocket-4.1.xsd">http://www.springframework.org/schema/websocket/spring-websocket-4.1.xsd</a>
客户端
- <script type="text/javascript"
- src="http://localhost:8080/Bank/js/sockjs-0.3.min.js"></script>
- <script>
- var websocket;
- if ('WebSocket' in window) {
- websocket = new WebSocket("ws://" + document.location.host + "/Bank/webSocketServer");
- } else if ('MozWebSocket' in window) {
- websocket = new MozWebSocket("ws://" + document.location.host + "/Bank/webSocketServer");
- } else {
- websocket = new SockJS("http://" + document.location.host + "/Bank/sockjs/webSocketServer");
- }
- websocket.onopen = function(evnt) {};
- websocket.onmessage = function(evnt) {
- $("#test").html("(<font color='red'>" + evnt.data + "</font>)")
- };
- websocket.onerror = function(evnt) {};
- websocket.onclose = function(evnt) {}
- $('#btn').on('click', function() {
- if (websocket.readyState == websocket.OPEN) {
- var msg = $('#id').val();
- //调用后台handleTextMessage方法
- websocket.send(msg);
- } else {
- alert("连接失败!");
- }
- });
- </script>
注意导入socketjs时要使用地址全称,并且连接使用的是http而不是websocket的ws
java 实现websocket的两种方式的更多相关文章
- WebSocket实践——Java实现WebSocket的两种方式
什么是 WebSocket? 随着互联网的发展,传统的HTTP协议已经很难满足Web应用日益复杂的需求了.近年来,随着HTML5的诞生,WebSocket协议被提出,它实现了浏览器与服务器的全双工通信 ...
- Java搭建WebSocket的两种方式
下面分别介绍搭建方法:一.直接使用Java EE的api进行搭建.一共3个步骤:1.添加依赖<dependency> <groupId>javax</groupId ...
- java 实现websocket的三种方式
Java中实现websocket常见有以下三种方式: 使用tomcat的websocket实现,需要tomcat 7.x,JEE7的支持. 使用spring的websocket,spring与webs ...
- 对Java代码加密的两种方式,防止反编译
使用Virbox Protector对Java项目加密有两种方式,一种是对War包加密,一种是对Jar包加密.Virbox Protector支持这两种文件格式加密,可以加密用于解析class文件的j ...
- Java新建线程的两种方式
Java新建线程有两种方式,一种是通过继承Thread类,一种是实现Runnable接口,下面是新建线程的两种方式. 我们假设有个竞赛,有一个选手A做俯卧撑,一个选手B做仰卧起坐.分别为两个线程: p ...
- Java实现多线程的两种方式
实现多线程的两种方式: 方式1: 继承Thread类 A: 自定义MyThread类继承Thread类 B: 在MyThread类中重写run() C: 创建MyThread类的对象 D: 启动线程对 ...
- [Java] HashMap遍历的两种方式
Java中HashMap遍历的两种方式原文地址: http://www.javaweb.cc/language/java/032291.shtml第一种: Map map = new HashMap( ...
- Java实现深克隆的两种方式
序列化和依次克隆各个可变的引用类型都可以实现深克隆,但是序列化的效率并不理想 下面是两种实现深克隆的实例,并且测试类对两种方法进行了对比: 1.重写clone方法使用父类中的clone()方法实现深克 ...
- java文件读写的两种方式
今天搞了下java文件的读写,自己也总结了一下,但是不全,只有两种方式,先直接看代码: public static void main(String[] args) throws IOExceptio ...
随机推荐
- 【centos6.5 hadoop2.7 _64位一键安装脚本】有问题加我Q直接问
#!/bin/bash#@author:feiyuanxing [既然笨到家,就要努力到家]#@date:2017-01-05#@E-Mail:feiyuanxing@gmail.com#@TARGE ...
- GO开发[五]:golang结构体struct
Go结构体struct Go语言的结构体(struct)和其他语言的类(class)有同等的地位,但Go语言放弃了包括继承在内的大量面向对象特性,只保留了组合(composition)这个最基础的特性 ...
- 火狐浏览器怎么查看页面加载了那些js文件,那系js文件有作用
方法一: 右击查看原代码,点击js链接如果能够看到文件内容,证明加载成功 方法二: 按F12键,如果控制台没有加载错误,证明加载成功:
- 微信公众平台宣布增加接口IP白名单提高安全性
微信公众平台目前已经发布通知在平台接口调用上为了提高安全性需要添加IP白名单并仅允许白名单IP调用. 目前微信公众平台面向开发者主要提供的开发者ID和开发者密钥,在调用时ID和密钥通过检验即可进行调用 ...
- 修真院java后端工程师学习课程--任务1(day four)
今天学习的是spring框架,内容主要有: spring的概念,主要是做什么的: Spring是一个基于IOC和AOP的结构J2EE系统的框架 IOC 反转控制 是Spring的基础,Inversio ...
- 深入理解final关键字以及一些建议
引子:一说到final关键字,相信大家都会立刻想起一些基本的作用,那么我们先稍微用寥寥数行来回顾一下. 一.final关键字的含义 final是Java中的一个保留关键字,它可以标记在成员变量.方法. ...
- RocketMQ-广播模式消费
Rocketmq 消费者默认是集群的方式消费的,消费者还可以用广播的模式进行消费.广播模式消费就是所有订阅同一个主题的消费者都会收到消息.代码实现上其实很简单,就是在消费端添加 consumer.se ...
- 捕获arm非托管磁盘虚拟机,并进行还原
背景:非托管磁盘虚拟机"hlmcen69n1",附加了一块100GB的数据磁盘.由于arm非托管磁盘机器无法通过Portal界面直接"Capture",故只能通 ...
- linux_运维职责
运维准则: 不要删文件,移动文件,可以复原,一个月后什么事没有,删除 运维人员主要关注哪些方面? CPU:对计算机工作速度和效率起决定性作用(intel amd) 内存: 临时存放数据:容量和处理速度 ...
- Django rest framework:__str__ returned non-string (type NoneType) 真正原因
出错原因: 用户表是Django中核心的表,当这个表类字段中有一个这样的函数 def __str__(self): return self.name 在Django用户表设计时候有个字段容易犯这个失误 ...