场景为用户发送 信息到服务器,服务器接收后,智能回复。用于聊天机器人。
1.maven环境加包
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-websocket-api</artifactId>
<version>7.0.47</version>
<scope>provided</scope>
</dependency>
2.Jfinal 配置文件修改(DemoConfig extends JFinalConfig )
public void configHandler(Handlers me) {
//me.add(new ContextPathHandler("contextPath"));
me.add(new WebSocketHandler("^/websocket"))
}
3.WebSocketHandler 文件
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);
}
}
4.接收信息发送信息
@ServerEndpoint("/websocket")
public class WebSocketTest {
public static CorpusService srv=CorpusService.me;
//静态变量,用来记录当前在线连接数。
private static AtomicInteger onlineCount = new AtomicInteger(0);
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
//protected static CopyOnWriteArraySet<WebSocketTest> webSocketSet = new CopyOnWriteArraySet<WebSocketTest>();
private static ConcurrentHashMap<String, WebSocketTest> webSocketSet = new ConcurrentHashMap<String, WebSocketTest>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
public WebSocketTest() {
System.out.println(" WebSocket init~~~");
}
/**
* 连接建立成功调用的方法
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(Session session){
System.out.println("新客人为" + session.getId());
this.session = session;
// webSocketSet.add(this); //加入set中
webSocketSet.put(session.getId(), this);//加入map中
addOnlineCount(); //在线数加1
System.out.println("有新连接"+session.getId()+"加入!当前在线人数为" + getOnlineCount());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(){
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
* @param session 可选的参数
* @throws IOException
* @throws InterruptedException
*/
@OnMessage
public void onMessage(String message, Session session) throws IOException, InterruptedException {
System.out.println("来自客户端的消息111:" + message);
//群发消息
getMessage(message,session);
//if (webSocketSet.get(session.getId()) != null) {
// webSocketSet.get(session.getId()).sendMessage("用户" + session.getId() + "发来消息:" + "<br/> " + message);
//}
//session.getAsyncRemote().sendText("##"+message);
//for(WebSocketTest item: webSocketSet){
// try {
// item.sendMessage(session.getId()+"说:"+message);
// } catch (IOException e) {
// e.printStackTrace();
// continue;
// }
// }
}
/**
* 发生错误时调用
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error){
System.out.println("发生错误");
error.printStackTrace();
}
/**
* 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException{
this.session.getBasicRemote().sendText(message);
//this.session.getAsyncRemote().sendText(message);
}
public static int getOnlineCount() {
return onlineCount.get();
}
public static void addOnlineCount() {
onlineCount.incrementAndGet();
}
public static void subOnlineCount() {
onlineCount.decrementAndGet();
}
public void getMessage(String msg,Session session) throws InterruptedException{
//获取数据
AiCorpus cor=srv.getCorpus(msg);
if(cor!=null){
String msgs=cor.getMessage();
String keywords=cor.getUsekeywords();
if(msgs.contains("/r/n")){
String[] strs=msgs.split("/r/n");
for(String str :strs){
if (webSocketSet.get(session.getId()) != null &&!"".equals(str)) {
try {
webSocketSet.get(session.getId()).sendMessage(str);
Thread.sleep(500);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}else
{
if (webSocketSet.get(session.getId()) != null &&!"".equals(msgs)) {
try {
webSocketSet.get(session.getId()).sendMessage(msgs);
Thread.sleep(500);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if (webSocketSet.get(session.getId()) != null &&!"".equals(keywords)) {
try {
webSocketSet.get(session.getId()).sendMessage("-->"+keywords);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else{
try {
webSocketSet.get(session.getId()).sendMessage("系统支持的词语:赠险是什么,保险是");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
5.测试工具:
http://coolaf.com/tool/chattest
6.请注意 默认jetty 环境不支持 websockt ,本人亲测 必在tomcat 8.5 下通过。