Server与Client建立连接后,会执行以下的步骤:
1、Client向Server发送消息
2、Server接收客户端发送的消息,并解析,根据解析内容向客户端发送消息
3、客户端接收到服务端消息,解析,根据解析结果,再发给客户端。
知道出现结束标志。
Server与Client建立连接后,会执行以下的步骤:
1、Client向Server发送消息
2、Server接收客户端发送的消息,并解析,根据解析内容向客户端发送消息
3、客户端接收到服务端消息,解析,根据解析结果,再发给客户端。
知道出现结束标志。
private void handleWebSocketFrame(ChannelHandlerContext ctx,
WebSocketFrame frame) {
// 是否关闭
if (frame instanceof CloseWebSocketFrame) {
if(null != ctx && null != ctx.channel()){
handshaker.close(ctx.channel(),
(CloseWebSocketFrame) frame.retain());
}
return;
}
// 是否ping
if (frame instanceof PingWebSocketFrame) {
ctx.channel().write(
new PongWebSocketFrame(frame.content().retain()));
return;
}
// 非文本
if (!(frame instanceof TextWebSocketFrame)) {
throw new UnsupportedOperationException(String.format(
"%s frame types not supported", frame.getClass().getName()));
}
// 接收到的消息
String msg = ((TextWebSocketFrame) frame).text();
// 发送者的通道
Channel incoming = ctx.channel();
if(StringUtils.isEmpty(msg)){
return;
}else if("@heart".equals(msg)){
// 收到心跳包,不做处理
// System.out.println("received[" + QuestionsAndAnswersUtil.getChannelUserId(incoming) + "]msg:" + msg);
return;
}else if ("1".equals(msg)){
return;
}
JSONObject jsonMsg = null;
try{
jsonMsg = JSONObject.fromObject(msg);
}catch(JSONException e){
}
if(null == jsonMsg){
// 收到的数据不是json格式数据,做普通聊天内容处理
dataCache.channels.writeAndFlush(new TextWebSocketFrame("["
+ QuestionsAndAnswersUtil.getChannelUserId(incoming) + "]:" + msg + "\n"+"online user num:"+dataCache.channels.size()));
return;
}
String type = jsonMsg.getString("type");
switch (type) {
case QuestionsAndAnswers.PackType.USER_ANSWER:
questionsAndAnswersService.userAnswer(ctx,jsonMsg);
break;
default:
break;
}