本次将连接人数、发送还是连接的状态、页面信息处理加以完善
如果您这边分开调用理解的不是太好可以借鉴我之前发布的websocket专题1~5参考查阅(忘记了是否都被发布)
WSController java文件主要用于处理页面发送过来的各个信息,不通指令做不同的处理
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.apache.log4j.Logger;
import org.sceu.tkdtas.constants.Constants;
import org.sceu.tkdtas.support.JSONResultSet;
import org.springframework.util.StringUtils;
import com.google.gson.Gson;@ServerEndpoint("/controller/{clientId}")
public class WSController extends WSBase{Logger log = Logger.getLogger(WSTimer.class);
Gson gson = new Gson();
private String clientId;
@Override
@OnMessage
public void onMessage(String msg, Session session) {
log.info("【REQ_MSG】:" + msg);
if(StringUtils.isEmpty(msg)) {
JSONResultSet js = new JSONResultSet();
js.setsCode(Constants.STATUS_CODE_400);
js.setMsg(Constants.STATUS_MSG_400);
try {
this.sendMessage(gson.toJson(js));}
catch (IOException e) {
log.error(e.getMessage(), e);
log.error("【"+getClientId()+"】与客户端连接已断开");}}
@SuppressWarnings("unchecked")
Map reqJsonMap = gson.fromJson(msg, HashMap.class);
String requestType = (String)reqJsonMap.get(Constants.WS_REQPARA_REQUESTTYPE);
log.info("REQUEST_TYPE:" + requestType);
WSControllerAdapter wSCAdapter = new WSControllerAdapter();
wSCAdapter.adapter(requestType, reqJsonMap);
}
@Override
@OnOpen
public void onOpen(@PathParam("clientId") String clientId, Session session) {
super.setSession(session);
if(StringUtils.isEmpty(clientId)) {
log.info("clientId is empty! clientId:" + clientId);
return ;
}
WebSocketPool.wsMap.put(clientId, this);
WebSocketPool.addOnLineCount();
}
public String getClientId() {
return clientId;
}
}
网友评论