package com.game.brag.server;
import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.plugins.mvc.websocket.AbstractWsEndpoint;
import org.nutz.plugins.mvc.websocket.NutWsConfigurator;
//ServerEndpoint是websocket的必备注解, value是映射路径, configurator是配置类.
//AbstractWsEndpoint深度封装了websocket的基础操作,继承可以实现许多封装好的基础功能
@ServerEndpoint(value = "/nutzWsServer/{roomId}/{openId}", configurator=NutWsConfigurator.class)
@IocBean
public class NutzWsServer extends AbstractWsEndpoint{
@Inject Dao dao;
@OnOpen
public void onOpen(Session session, EndpointConfig config,@PathParam("roomId") String roomId,
@PathParam("openId") String openId){
//调用父类的open
super.onOpen(session, config);
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
//调用父类的onclose
super.onClose(session, closeReason);
}
@OnError
public void onError(Session session, java.lang.Throwable throwable) {
//调用父类的onError
super.onError(session, throwable);
}
}
这些都是对单个对象单独发送消息的封装,没有房间群发的功能
/**
* 异步非阻塞发送文本信息到指定的WebSocket Session
*
* @param wsid
* session的id
* @param text
* 文本信息
* @return session存活即返回true
*/
public boolean sendText(String wsid, CharSequence text) {
Session session = getSession(wsid);
if (session == null)
return false;
session.getAsyncRemote().sendText(text.toString());
return true;
}
/**
* sendText的同步阻塞版本
*
* @param wsid
* session的id
* @param text
* 文本信息
* @return session存活且发送成功,返回true,否则返回false
*/
public boolean sendTextSync(String wsid, CharSequence text) {
Session session = getSession(wsid, true);
if (session == null)
return false;
try {
session.getBasicRemote().sendText(text.toString());
}
catch (IOException e) {
return false;
}
return true;
}
还有下面这个遍历活跃对象是干嘛?没有返回的东西?只是为了纯粹遍历一遍吗
/**
* 按房间遍历活跃的session对象
*
* @param room
* @param callback
*/
public void each(String room, final Each<Session> callback) {
Set<String> wsids = roomProvider.wsids(room);
if (wsids == null || wsids.isEmpty())
return;
// 需要先转为数组,因为Set经常增减的,直接foreach会挂.
String[] tmp = wsids.toArray(new String[wsids.size()]);
Lang.each(tmp, new Each<String>() {
public void invoke(int index, String ele, int length)
throws ExitLoop, ContinueLoop, LoopException {
Session session = getSession(ele);
if (session != null)
callback.invoke(index, session, length);
}
});
}