本文适用于知道Websock概念,但从未上手做过Demo的小白。
本文使用IDE为Intellij IDEA,Java version 1.8.0_172,Tomcat version 8.5.32。
项目下载地址:https://gitee.com/starCat/websocket_demo
一、小白必须具备的技能
1、会使用maven构建工程
2、会使用Spring
3、了解websocket
二、正式开战
项目目录一览,按照图示位置放好jquery和sockjs。
第一步,使用Maven建立一个Webapp工程,加入咱们工程所需要的依赖(应该是最简了,多余的一个也没加),如下:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>cn.justsoul.studygroupId>
<artifactId>websocket_demoartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<properties>
<spring.version>4.3.10.RELEASEspring.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-websocketartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-context-supportartifactId>
<version>${spring.version}version>
dependency>
dependencies>
project>
第二步,配置spring,直接上代码
spring.xml
<context:annotation-config/>
<context:component-scan base-package="cn.justsoul.study"/>
spring_mvc.xml
<context:component-scan base-package="cn.justsoul.study" />
<mvc:annotation-driven/>
<mvc:resources mapping="/js/**" location="/js/"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
第三步,配置web.xml,没啥好说的,直接上代码
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring_mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
重点开始了
第四步,创建我们自己的Websocket拦截器。新建一个MyHandshakeInterceptor类继承自HttpSessionHandshakeInterceptor,我们用他来处理建立Tcp握手之前和之后要干的事情。这里就简单的在控制台打印点东西好了:)
public class MyHandshakeInterceptor extends HttpSessionHandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map attributes) throws Exception {
System.out.println("beforeHandshake");
return super.beforeHandshake(request, response, wsHandler, attributes);
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
System.out.println("afterHandshake");
super.afterHandshake(request, response, wsHandler, ex);
}
}
第五步,有了拦截器,我们还需要一个处理器来处理连接之后的事情,所以我们
新建一个MyWebSocketHandler类继承自AbstractWebSocketHandler,也可以继承AbstractWebSocketHandler的子类,他们各有其功能,这个项目我们用不到就选AbstractWebSocketHandler就够用了。重写afterConnectionEstablished与afterConnectionClosed方法,来实现“连接创建之后”以及“连接关闭之后”我们要干的事情。这里也是简单的在控制台打印点东西好了:)
public class MyWebSocketHandler extends AbstractWebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
System.out.println("afterConnectionEstablished");
super.afterConnectionEstablished(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
System.out.println("afterConnectionClosed");
super.afterConnectionClosed(session, status);
}
}
第六步,新建WebSocketConfig类,我们使用它来加载咱们的拦截器和处理器,使能建立websocket连接。
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
String websocket_url = "/websocket/socketServer.do";
registry.addHandler(new MyWebSocketHandler(), websocket_url).addInterceptors(new MyHandshakeInterceptor());
String sockjs_url = "/sockjs/socketServer.do";
registry.addHandler(new MyWebSocketHandler(), sockjs_url).addInterceptors(new MyHandshakeInterceptor()).withSockJS();
}
}
这里sockjs方式主要是为了支持有些不支持ws连接方式的浏览器:)
第七步,随便做个页面和控制器:)
WebSocketController
@Controller
class WebSocketController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView goIndex(){
ModelAndView mv = new ModelAndView();
mv.setViewName("index");
return mv;
}
}
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Websocket Demotitle>
head>
<body>
Websocket Demo
<hr>
<button id="ws">使用ws创建连接button>
<button id="sockjs">使用sockjs创建连接button>
<button id="close">关闭websocket连接button>
body>
html>
<script type="text/javascript" src="js/jquery-3.2.1.min.js">script>
<script type="text/javascript" src="js/sockjs-1.1.0.min.js">script>
<script type="text/javascript">
$(function () {
$("#ws").click(function () {
ws_connect();
});
$("#sockjs").click(function () {
sockjs_connect();
});
$("#close").click(function () {
websocket.close();
});
});
function ws_connect() {
websocket = new WebSocket("ws://localhost:8080/websocket_demo/websocket/socketServer.do");
}
function sockjs_connect() {
websocket = new SockJS("http://localhost:8080/websocket_demo/sockjs/socketServer.do");
}
script>
好了,所有的工作都做完了,运行一下,看看效果吧。这里需要注意的是,websocket请求地址一定要结合你自己的环境配置正确设置。怎么样,是不so easy?
什么?你不想搞这么多事,只想连上websocket,用它来发个消息啥的,早说嘛,来看看这个