由于公司框架陈旧,现在还在使用struts1框架,但在写一个功能的时候,又不得已用到websocket,不得不探讨一下,在struts下如何使用websocket。
和struts2框架不同,struts1中没有过滤器功能,因此不需在struts.xml中配置 <constant name="struts.action.excludePattern" value="/websocket*,^ws://.$"/>
错了,struts1是配置struts-config.xml,也就是说,struts-config.xml中不需要做任何配置,本人曾尝试在web.xml中配置servlet,和servletMaping,但没什么卵用,
最后发现,只要包引对就好了,之前使用的maven配置,不对,最后在tomcat下,找到这两个包,build path一下,就好了。
server端使用
@ServerEndpoint("/websocket")
public class WebSocket {
@OnOpen
public void open(Session session) {
// 添加初始化操作
System.out.println("正在连接");
}
/**
* 接受客户端的消息,并把消息发送给所有连接的会话
* @param message 客户端发来的消息
* @param session 客户端的会话
*/
@OnMessage
public void getMessage(String message, Session session) {
//TODO
System.out.println("收到消息");
try {
session.getBasicRemote().sendText("{'message':'ni hao ,shou dao xiao xi.'}");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@OnClose
public void close() {
// 添加关闭会话时的操作
}
@OnError
public void error(Throwable t) {
// 添加处理错误的操作
System.out.println(t.getMessage());
System.out.println(t.getCause());
t.printStackTrace();
}
}
html5端:
if(!("WebSocket" in window)){
alert("bu zhi chi WebSocket");
}
// 创建一个Socket实例
try{
socket = new WebSocket('ws://localhost:8081/AssistSystem/websocket');
}catch(e){
console.log(e);
}
// 打开Socket
socket.onopen = function(event) {
console.log("打开Socket");
};
// 监听消息
socket.onmessage = function(event) {
console.log('Client received a message',event);
};
// 监听Socket的关闭
socket.onclose = function(event) {
console.log('Client notified socket has closed',event);
};
// 关闭Socket....
//socket.close()
一切搞定!