config
@Override
public void configHandler(Handlers me) {
me.add(new WebSocketHandler("/websocket"));
}
@ServerEndpoint("/websocket.ws")
public class WebSocketController {
@OnOpen
public void onOpen(Session session) {
System.out.println("连接打开了OPEN");
}
/**
* 收到客户端消息时触发
*/
@OnMessage
public void onMessage(Session session, String key) throws IOException {
//向客户端返回发送过来的消息
System.out.println("发送一条消息:--"+key);
session.getBasicRemote().sendText(key);//推送发送的消息
}
/**
* 异常时触发
*/
@OnError
public void onError(Throwable throwable,Session session) {}
/**
* 关闭连接时触发
*/
@OnClose
public void onClose(Session session) {
System.out.println("连接关闭了~~~~(>_<)~~~~");
}
}
public class WebSocketHandler extends Handler {
private Pattern filterUrlRegxPattern;
public WebSocketHandler(String filterUrlRegx) {
if (StrKit.isBlank(filterUrlRegx))
throw new IllegalArgumentException("The para filterUrlRegx can not be blank.");
filterUrlRegxPattern = Pattern.compile(filterUrlRegx);
}
@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
if (filterUrlRegxPattern.matcher(target).find()) {
return;
} else {
next.handle(target, request, response, isHandled);
}
}
}
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-websocket-api</artifactId>
<version>7.0.47</version>
<scope>compile</scope>
</dependency>在jetty-server 下进行开发时,WebSocket的配置方式是这样吗
项目:JFinal
高版本的 servlet 可以通过注解来添加 websocket
建议使用 jfinal undertow ,支持 websocket 很方便,这里有添加 websocket 的文档:
https://jfinal.com/doc/1-4