1.创建maven web工程
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<groupId>com.cairh.websocket</groupId>
<artifactId>demo-websocket</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax/javaee-api -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- 配置Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>8082</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
## 2.websocket的相关注解说明
**@ServerEndpoint("/websocket/{uid}")**
申明这是一个websocket服务
需要指定访问该服务的地址,在地址中可以指定参数,需要通过{}进行占位
**@OnOpen**
用法:public void onOpen(Session session, @PathParam("uid") String uid) throws
IOException{}
该方法将在建立连接后执行,会传入session对象,就是客户端与服务端建立的长连接通道
通过@PathParam获取url申明中的参数
**@OnClose**
用法:public void onClose() {}
该方法是在连接关闭后执行
**@OnMessage**
用法:public void onMessage(String message, Session session) throws IOException {}
该方法用于接收客户端发来的消息
message:发来的消息数据
session:会话对象(也是通道)
发送消息到客户端
用法:session.getBasicRemote().sendText("你好");
通过session进行发送。
## 3.实现websocket服务
@ServerEndpoint("/websocket/{uid}")
public class MyWebSocket {
/**
* 建立连接
*/
@OnOpen
public void open(Session session, @PathParam("uid") String uid) throws IOException {
// 向客户端发送消息
session.getBasicRemote().sendText(uid+ ",你好,欢迎连接WebSocket!");
}
/**
* 连接关闭
*/
@OnClose
public void onclose(){
System.out.println(this + "关闭连接");
}
/**
*
* @param message 客户端发送来的消息
* @param session
* @throws IOException
*/
@OnMessage
public void onMessage(String message, Session session) throws IOException {
System.out.println("接收到消息:" + message);
session.getBasicRemote().sendText("消息已收到."); // 向客户端发送消息
}
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
}
4.启动服务
启动tomcat
5.测试
1.可以通过安装chrome插件或者通过在线工具进行测试:
chrome插件,Simple WebSocket Client:
https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo
2.在线工具:http://www.easyswoole.com/wstool.html
从图中可以看到webSocket建立连接了,同时向客户端发送了消息
代码:
6.编写js客户端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
const socket = new WebSocket("ws://localhost:8082/websocket/1");
socket.onopen = (ws) => {
console.log("建立连接", ws);
}
socket.onmessage = (ws) =>{
console.log("接收到消息 >> ",ws.data);
}
socket.onclose = (ws) =>{
console.log("连接已断开!", ws);
}
socket.onerror = (ws) => {
console.log("发送错误!", ws);
}
// 2秒后向服务端发送消息
setTimeout(()=>{
socket.send("发送一条消息试试");
},2000);
// 5秒后断开连接
setTimeout(()=>{
socket.close();
},5000);
</script>
</body>
</html>
查看控制台