webSocket的原理在此我就不多bb了,网上有很多,建议初学的小伙伴先移步[教程] (https://www.cnblogs.com/tohxyblog/p/7112917.html)讲的很生动,我今天说的主要 是基于springboot的websocket,很简单,废话不多说了,直接上代码。。。。。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
```import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint(value = "/websocket/{myUserId}")
@Component
public class MyWebSocket {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//存放用户的id与session关系
private static HashMap<String, Session> map = new HashMap();
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(@PathParam("myUserId") String myUserId, Session session) {
if (myUserId != null) {
//从url中获取当前用户的id和其session做对应
map.put(myUserId, session);
}
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
try {
sendMessage("连接成功", session);
} catch (IOException e) {
System.out.println("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
Collection<Session> values = map.values();
values.remove(this);//从map中移除用户session
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
String[] split = message.split("-");//获取用户发送的信息和发送人id
System.out.println("来自客户端的消息:" + split[0]);
try {
Session session1 = map.get(split[1]);
if (session1 == null) {
sendMessage("该用户不在线", session);
} else {
sendMessage(split[0], session1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
/**
* 通过session确认给谁发信息
*
* @param session
* @param message
*/
public void sendMessage(String message, Session session) throws IOException {
session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
*/
public static void sendInfo(String message) throws IOException {
System.out.println(message);
for (MyWebSocket item : webSocketSet) {
try {
item.sendMessage(message, item.session);
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyWebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyWebSocket.onlineCount--;
}
}
<!DOCTYPE HTML>
<html>
<head>
<title>My WebSocket</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text"/>
<button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
</br>
<input id="toUserId" type="text">To user id</br>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
var sHref = window.location.href;
var myUserId = sHref.split("&")[1];//从url获取用户的id
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/websocket/" + myUserId);
}
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 + '<br/>';
}
//关闭连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById('text').value;
var toUserId = document.getElementById('toUserId').value;
websocket.send(message + "-" + toUserId);
}
</script>
</html>
测试:
至此,点对点发送信息完成。但要注意的的是我浏览器上边&后跟着的是当前登陆用户id(真实开发环境需要前端获取传递到后端,现在只是模拟),然后我们再来说下点对面发送。
/**
* 群发自定义消息
*/
public static void sendInfo(String message) throws IOException {
System.out.println(message);
for (MyWebSocket item : webSocketSet) {
try {
item.sendMessage(message, item.session);
} catch (IOException e) {
continue;
}
}
}
核心就是这个方法,有细心的小伙伴会发现webSocket发送信息是通过session来确定发送对象的,所有我们就遍历实例获取所有session,是不是很简单,附上我的controller
@RequestMapping(path = "sendMessage")
public Map<String, Object> sendMessage(@RequestBody Map<String, Object> map) {
Map<String,Object> result =new HashMap<String,Object>();
try {
myWebSocket.sendInfo("有新客户呼入,sltAccountId:"+map.get("sltAccountId"));
result.put("operationResult", true);
}catch (IOException e) {
result.put("operationResult", true);
}
return result;
}
看下运行效果
有不对的地方欢迎大家指出,随时改正(愿天堂没有加班,阿门…)。