1.简介:WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器实现持久连接的全双工双向通信,客户端可以主动的向服务器发起请求以获取数据,服务器也可以主动向客户端返回响应以传输数据。
在JS中创建WebSocket后,会有一个HTTP请求发向浏览器以发起请求。在取得服务器响应后,建立的连接会使用HTTP升级将HTTP协议转换为WebSocket协议。
也就是说,使用标准的HTTP协议无法实现WebSocket,只有支持那些协议的专门浏览器才能正常工作。
WebSocket是应用层协议,是TCP/IP协议的子集,通过HTTP/1.1协议的101状态码进行握手。也就是说,WebSocket协议的建立需要先借助HTTP协议,在服务器返回101状态码之后,就可以进行websocket全双工双向通信了,就没有HTTP协议什么事情了。
WebScoket使用了自定义协议,所以URL与HTTP协议略有不同。未加密的连接为ws://,而不是http://。加密的连接为wss://,而不是https://。
2.推送:
1.传统推送采用ajax轮询,是客户端向服务器发起HTTP请求,无论数据是否更新,服务器都会传输数据,一个request对应一个response。
2.dwr推送,一个类似于ajax的框架,可以将后台代码转换成js,前端页面js调用后台,也可以后台推送前端。
3.websocket推送,客户端与服务器建立http连接,服务端可以随时向客户端进行推送。
3.用法:
一、java websocket
1.下载java websocket包,maven下载
<!-- java-websocket -->
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
2.java websocket类
package com.ss.websocket;
import org.springframework.beans.factory.annotation.Autowired;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
//要求:Tomcat从7.0.27开始支持WebSocket,从7.0.47开始支持JSR-356,下面的Demo代码也是需要部署在Tomcat7.0.47上才能运行。
//该注解用来指定一个URI,客户端可以通过这个URI来连接到WebSocket。类似Servlet的注解mapping。无需在web.xml中配置。
@ServerEndpoint("/javaWebsocket")
public class JavaWebsocket {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static CopyOnWriteArraySet<JavaWebsocket> webSocketSet = new CopyOnWriteArraySet<JavaWebsocket>();
private static Map<Session,JavaWebsocket> websocketMap = new HashMap();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
/**
* 连接建立成功调用的方法
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(Session session){
this.session = session;
webSocketSet.add(this); //加入set中
websocketMap.put(session,this);
System.out.println("有新连接加入!当前在线人数为" +websocketMap.size());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(){
webSocketSet.remove(this); //从set中删除
websocketMap.remove(this);
System.out.println("有一连接关闭!当前在线人数为" +websocketMap.size());
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println(session.getId()+"来自客户端的消息:" + message);
//群发消息
/*
for(JavaWebsocket item: webSocketSet){
try {
item.sendMessage("您好:"+message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
*/
//一对一单发消息
try{
JavaWebsocket ws = websocketMap.get(session);
ws.sendMessage("您好:"+message);
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 发生错误时调用
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error){
System.out.println("发生错误");
websocketMap.remove(session);
error.printStackTrace();
}
/**
* 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException{
this.session.getBasicRemote().sendText(message);
//this.session.getAsyncRemote().sendText(message);
}
}
3.页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script type="text/javascript">
var websocket = null;
var host = window.location.host;//获取当前服务器ip:port
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
websocket = new WebSocket("ws://"+host+"/${basePath}/javaWebsocket");
}else{
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function(event){
setMessageInnerHTML("open");
}
//接收到消息的回调方法
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 + '
';
}
//关闭连接
function closeWebSocket(){
websocket.close();
}
//发送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
<body>
java websocket测试<br/>
<input id="text" type="text" /><button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message"></div>
</body>
</html>
4.运行结果
二、spring websocket
1.下载spring-websocket包。maven下载与自己spring一致的版本
<!-- spring-websocket -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
2.spring socket配置类
package com.ss.config;
import com.ss.websocket.SpringWebSocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
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;
/**
* spring websocket配置类
*/
@Configuration
@EnableWebMvc
@EnableWebSocket
public class SpringWebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
//.setAllowedOrigins(sites);设置运行跨域,setAllowedOrigins("*"); *代表所有
//设置允许跨域的站点
String[] sites={"http://www.baidu.com","http://www.csdn.net"};
//添加连接通道
registry.addHandler(webSocketHandler(),"/websocket/springWebsocket").addInterceptors(new SpringWebSocketInterceptor()).setAllowedOrigins(sites);
registry.addHandler(webSocketHandler(), "/sockjs/springWebsocket").addInterceptors(new SpringWebSocketInterceptor()).withSockJS();
}
@Bean
public TextWebSocketHandler webSocketHandler(){
return new SpringWebSocket();
}
}
3.spring socket接收推送类
package com.ss.websocket;
import com.ss.service.system.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* spring socket接收推送类
*/
public class SpringWebSocket extends TextWebSocketHandler {
@Autowired
private UserService userService;
private static Map<WebSocketSession, SpringWebSocket> websocketMap = new HashMap<>();
public SpringWebSocket() {
}
/**
* 连接成功时候,会触发页面上onopen方法
*/
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
websocketMap.put(session, this);
System.out.println("connect to the websocket success......当前在线数量:" + websocketMap.size());
//这块会实现自己业务,比如,当用户登录后,会把离线消息推送给用户
//TextMessage returnMessage = new TextMessage("你将收到的离线");
//session.sendMessage(returnMessage);
}
/**
* 关闭连接时触发
*/
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
System.out.println("用户" + session.getId() + "已退出!");
websocketMap.remove(session);
System.out.println("剩余在线用户" + websocketMap.size());
}
/**
* js调用websocket.send时候,会调用该方法
*/
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
System.out.println(session.getId() + "发来消息:" + message);
websocketMap.get(session).sendMessageToUser(session,message);
super.handleTextMessage(session, message);
}
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
if (session.isOpen()) {
session.close();
}
websocketMap.remove(session);
}
public boolean supportsPartialMessages() {
return false;
}
/**
* 给某个用户发送消息
*
* @param session
* @param message
*/
public void sendMessageToUser(WebSocketSession session, TextMessage message) {
int cc = userService.getUserCount(0,null);
System.out.println("数据库用户数"+cc);
System.out.println("--"+message.getPayload());
WebSocketMessage msg = new TextMessage("您好:"+message.getPayload());
try {
if (session.isOpen()) {
session.sendMessage(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 给所有在线用户发送消息
*
* @param message
*/
public void sendMessageToAllUser(TextMessage message) {
Set<WebSocketSession> ks = websocketMap.keySet();
for (WebSocketSession key : ks) {
try {
if (key.isOpen()) {
key.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4.spring websocket拦截器
package com.ss.config;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
import javax.servlet.http.HttpSession;
import java.util.Map;
/**
* spring WebSocket拦截器
*
*/
public class SpringWebSocketInterceptor extends HttpSessionHandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
//只在页面初始化打开连接时调用
System.out.println("spring WebSocket拦截器 ...Before Handshake");
return super.beforeHandshake(request, response, wsHandler, attributes);
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Exception ex) {
super.afterHandshake(request, response, wsHandler, ex);
}
}
5.把拦截器加入spring配置中
导入websocket标签
xmlns:websocket="http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket/spring-websocket.xsd
配置拦截器
<!-- spring socket拦截器-->
<bean id="springWebocketHandler" class="com.ss.websocket.SpringWebSocket"/>
<bean id="springWebocketInterceptor" class="com.ss.config.SpringWebSocketInterceptor"/>
<websocket:handlers >
<websocket:mapping path="/websocket" handler="springWebocketHandler"/>
<websocket:handshake-interceptors>
<ref bean="springWebocketInterceptor"/>
</websocket:handshake-interceptors>
</websocket:handlers>
6.页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="${basePath}/static/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="${basePath}/static/js/reconnecting-websocket.min.js"></script>
<script type="text/javascript" src="${basePath}/static/js/sockjs-1.15.min.js"></script>
</head>
<script>
var host = window.location.host;//获取当前服务器ip:port
console.log(host);
var websocket = null;
if ('WebSocket' in window) {
websocket = new WebSocket("ws://"+host+"/app/websocket/springWebsocket");
//websocket = new ReconnectingWebSocket("ws://"+ host + "/app/websocket/springWebsocket", null, {debug:true, maxReconnectAttempts:4});
}else if ('MozWebSocket' in window) {
websocket = new MozWebSocket("ws://"+host+"/app/websocket/springWebsocket");
}else {
websocket = new SockJS("http://"+host+"/app/sockjs/springWebsocket");
}
//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function(event){
setMessageInnerHTML("open");
}
//接收到消息的回调方法
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 + '
';
}
//关闭连接
function closeWebSocket(){
websocket.close();
}
//发送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
<body>
spring websocket测试<br/>
<input id="text" type="text" /><button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message"></div>
</body>
</html>
7.运行结果