java WebSocket实现Java后台消息推送
1.什么是WebSocket
2.实现原理
3.优点
4.WebSocket和Socket的区别
1.WebSocket:
2.Socket:
5.WebSocket客户端:
var websocket = null;
var host = document.location.host;
var username = "${loginUsername}"; // 获得当前登录人员的userName
// alert(username)
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
alert("浏览器支持Websocket")
websocket = new WebSocket('ws://'+host+'/mm-dorado/webSocket/'+username);
} else {
alert('当前浏览器 Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function() {
alert("WebSocket连接发生错误")
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function() {
alert("WebSocket连接成功")
setMessageInnerHTML("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function(event) {
alert("接收到消息的回调方法")
alert("这是后台推送的消息:"+event.data);
websocket.close();
alert("webSocket已关闭!")
}
//连接关闭的回调方法
websocket.onclose = function() {
setMessageInnerHTML("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
closeWebSocket();
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
6.WebSocket服务端(java后台):
package com.mes.util;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.google.gson.JsonObject;
import net.sf.json.JSONObject;
@ServerEndpoint("/webSocket/{username}")
public class WebSocket {
private static int onlineCount = 0;
private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
private Session session;
private String username;
@OnOpen
public void onOpen(@PathParam("username") String username, Session session) throws IOException {
this.username = username;
this.session = session;
addOnlineCount();
clients.put(username, this);
System.out.println("已连接");
}
@OnClose
public void onClose() throws IOException {
clients.remove(username);
subOnlineCount();
}
@OnMessage
public void onMessage(String message) throws IOException {
JSONObject jsonTo = JSONObject.fromObject(message);
String mes = (String) jsonTo.get("message");
if (!jsonTo.get("To").equals("All")){
sendMessageTo(mes, jsonTo.get("To").toString());
}else{
sendMessageAll("给所有人");
}
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public void sendMessageTo(String message, String To) throws IOException {
// session.getBasicRemote().sendText(message);
//session.getAsyncRemote().sendText(message);
for (WebSocket item : clients.values()) {
if (item.username.equals(To) )
item.session.getAsyncRemote().sendText(message);
}
}
public void sendMessageAll(String message) throws IOException {
for (WebSocket item : clients.values()) {
item.session.getAsyncRemote().sendText(message);
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
public static synchronized Map<String, WebSocket> getClients() {
return clients;
}
}
2.在自己代码中的调用:
WebSocket ws = new WebSocket();
JSONObject jo = new JSONObject();
jo.put("message", "这是后台返回的消息!");
jo.put("To",invIO.getIoEmployeeUid());
ws.onMessage(jo.toString());
7.所需maven依赖:
<!-- webSocket 开始-->
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<!-- webSocket 结束-->
正文到此结束
- 本文标签: Java
-
声明&链接
本站原创文章,于2020年10月29日由51soupan.cn发布,转载请注明出处
热门推荐
相关文章
该篇文章的评论功能已被站长关闭