事务(Transaction)总结
1. 首先建立一个SpringBoot项目,指定端口号为10000(可自由设置)
2. 在pom.xml文件里引入websocket包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
3. 建立WebSocketConfig配置文件
@Configuration
public class WebSocketConfig {
[@Bean](https://my.oschina.net/bean)
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
4. 建立WebSocketServer类
@ServerEndpoint("/websocket")
[@Component](https://my.oschina.net/u/3907912)
[@Slf4j](https://my.oschina.net/slf4j)
@Scope("prototype")
public class WebSocketServer {
//静态变量,用来记录当前在线链接数
private static final AtomicInteger onlineCount = new AtomicInteger(0);
//concurrent包的线程安全Set,用来存放每一个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<Session> sessionSet = new CopyOnWriteArraySet<>();
public static void sendMessage(Session session, String message) {
try {
session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)", message, session.getId()));
} catch (IOException e) {
log.error("发送消息出错:{}", e.getMessage());
e.printStackTrace();
}
}
/**
* 群发消息
*/
public static void BroadCastInfo(String message) throws IOException {
for (Session session : sessionSet) {
if (session.isOpen()) {
sendMessage(session, "收到消息,消息内容:" + message);
}
}
}
/**
* 指定Session发送消息
*
* @param sessionId
* @param message
* @throws IOException
*/
public static void SendMessage(String sessionId, String message) throws IOException {
Session session = null;
for (Session s : sessionSet) {
if (s.getId().equals(sessionId)) {
session = s;
break;
}
}
if (session != null) {
sendMessage(session, message);
} else {
log.warn("没有找到你指定ID的会话:{}", sessionId);
}
}
/**
* 链接成功 调用
*/
@OnOpen
public void onOpen(Session session) {
sessionSet.add(session);
log.info("有新窗口开始监听,当前在线人数为" + onlineCount.incrementAndGet());
}
/**
* 链接关闭调用的方法
*/
@OnClose
public void onClose(Session session) {
sessionSet.remove(session);
log.info("有一链接关闭!当前在线人数为" + onlineCount.decrementAndGet());
}
/**
* 接客户端消息
*
* @param message 客户端发送消息
* @param session
*/
@OnMessage
public void onMessage(String message, Session session) throws IOException {
log.info("收到来自窗口的信息:" + message);
BroadCastInfo("收到消息,消息内容:" + message);
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误:{},Session ID: {}", error.getMessage(), session.getId());
error.printStackTrace();
}
}
5. 建立restful接口,用于服务端手工推送任务
@RestController
@RequestMapping("/api/ws")
public class WebSocketController {
/**
* 群发消息内容
*
* @param message
* @return
*/
@RequestMapping(value = "/sendAll", method = RequestMethod.GET)
public String sendAllMessage(@RequestParam String message) {
try {
WebSocketServer.BroadCastInfo(message);
} catch (IOException e) {
e.printStackTrace();
}
return "ok";
}
/**
* 指定会话ID发消息
*
* @param message 消息内容
* @param id 链接会话ID
* @return
*/
@RequestMapping(value = "/sendOne", method = RequestMethod.GET)
public String sendOneMessage(@RequestParam String message,
@RequestParam String id) {
try {
WebSocketServer.SendMessage(id, message);
} catch (IOException e) {
e.printStackTrace();
}
return "ok";
}
}
6. 建立前端测试页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>websocket测试</title>
<style type="text/css">
h3,h4{
text-align:center;
}
</style>
</head>
<body>
<h3>WebSocket测试,在<span style="color:red">控制台</span>查看测试信息输出!</h3>
<h4>http://wallimn.iteye.com</h4>
<h4>
[url=/api/ws/sendOne?message=单发消息内容&id=none]单发消息连接[/url]
[url=/api/ws/sendAll?message=群发消息内容]群发消息连接[/url]
</h4>
<div id="msgDiv" style="width: 400px;height: 300px;background-color: bisque;"></div>
<textarea id="msgTxt"></textarea>
<input type="button" onclick="sendMsg()" value="发送">
<script type="text/javascript">
var socket;
if (typeof (WebSocket) == "undefined") {
console.log("遗憾:您的浏览器不支持WebSocket");
} else {
console.log("恭喜:您的浏览器支持WebSocket");
//实现化WebSocket对象
//指定要链接的服务器地址与端口创建链接
//注意ws、wss使用不一样的端口。我使用自签名的证书测试,
//没法使用wss,浏览器打开WebSocket时报错
//ws对应http、wss对应https。
socket = new WebSocket("ws://localhost:10000/websocket");
//链接打开事件
socket.onopen = function() {
console.log("Socket 已打开");
socket.send("消息发送测试(From Client)");
};
//收到消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
document.getElementById("msgDiv").append("<p>"+msg.data+"</p>");
};
//链接关闭事件
socket.onclose = function() {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
alert("Socket发生了错误");
}
//窗口关闭时,关闭链接
window.unload=function() {
socket.close();
};
}
function sendMsg(){
var msg=document.getElementById("msgTxt").value;
socket.url
socket.send(msg);
}
</script>
</body>
</html>