struts2框架如何使用websocket实现web程序消息推送
·
struts2框架如何使用websocket实现web程序消息推送
博主近期正在学用struts2开发web程序,突然想到想在自己的web程序里实现站内消息推送的功能,也就是根据需要,后端根据需要向前端推送消息,经过一番在网上查找资料,了解到可以通过websocket来实现消息推送,但发现网上大多数的示例代码要嘛有错,要嘛不全,终于找到一个好一点的实例代码,现在分享给大家,献给同样有需求的人,避免走弯路~
websocket + struts2实现消息推送其实很简单,示例代码如下:
java代码:
@ServerEndpoint("/ws/websocket")
public class WebSocketTest {
@OnMessage
public void onMessage(String message,Session session)
throws IOException, InterruptedException
{
System.out.println("***************");
session.getBasicRemote().sendText(" this is message");
int sentMessage = 0;
while(sentMessage < 3){
Thread.sleep(5000);
session.getBasicRemote().sendText(" this is one mess " + sentMessage);
sentMessage++;
}
session.getBasicRemote().sendText(" message send over ");
}
@OnOpen
public void onOpen(){
System.out.println(" client connected ");
}
@OnClose
public void onClose(){
System.out.println(" connection closed ");
}
}
使用@ServerEndpoint(“/ws/websocket”)即可进行访问
前端jsp代码如下:
<!DOCTYPE html>
<html>
<head>
<title>Testing websockets</title>
</head>
<body>
<div>
<input type="submit" value="Start" onclick="start()" />
</div>
<div id="messages"></div>
<script type="text/javascript">
var webSocket;
if ('WebSocket' in window) {
webSocket = new WebSocket("ws://localhost:8080/Backstage/ws/websocket");
} else if ('MozWebSocket' in window) {
webSocket = new MozWebSocket("ws://localhost:8080/websocket");
} else {
alert("js");
webSocket = new SockJS("http://localhost:8080/Origami/sockjs/webSocketServer");
}
webSocket.onerror = function(event) {
onError(event)
};
webSocket.onopen = function(event) {
onOpen(event)
};
webSocket.onmessage = function(event) {
onMessage(event)
};
function onMessage(event) {
document.getElementById('messages').innerHTML
+= '<br />' + event.data;
}
function onOpen(event) {
document.getElementById('messages').innerHTML
= 'Connection established';
}
function onError(event) {
//console.log(event);
//console.log(event.data);
alert(event.data);
}
function start() {
webSocket.send('hello');
return false;
}
</script>
</body>
</html>
运行结果:
可能有的人会碰到这样的问题:
浏览器无法建立到 ws://localhost:8080/XXXXX/ws/websocket 服务器的连接。(XXXXX为你的项目名称)
webSocket = new WebSocket(“ws://localhost:8080/XXXXX/ws/websocket”);
出现这个是因为使用了struts2过滤器,web.xml中配置了struts2 过滤为/*,所以导致所有的请求都被拦截了。解决办法也很简单:
struts.xml文件中加上
<constant name="struts.action.excludePattern" value="/ws/.*,ws://.*"></constant>
过滤掉ws://请求即可
OK!搞定~
更多推荐



所有评论(0)