用websocket做了个聊天功能,在电脑端可以正常使用。但在手机端却不能使用。就是在手机端登陆的时候获取不到用户的id.
3条回答 默认 最新
- fassbenderjs 2015-12-08 09:54关注
package com.jp100.wapbaike.service;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;
import org.apache.log4j.Logger;@SuppressWarnings("deprecation")
public class WebSocketInboundImpl extends MessageInbound {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(WebSocketInboundImpl.class);
private String userId ;public WebSocketInboundImpl(String userId){ this.userId = userId; } /** * 打开 */ protected void onOpen(WsOutbound outbound) { WebSocketService.getMessageInbound().add(this); logger.debug("onOpen(WsOutbound) this" + this); //$NON-NLS-1$ super.onOpen(outbound); } /** * 关闭 */ protected void onClose(int status) { WebSocketService.getMessageInbound().remove(this); super.onClose(status); } /** * 流处理 */ protected void onBinaryMessage(ByteBuffer arg0) throws IOException { for (MessageInbound bmsg : WebSocketService.getMessageInbound()) { ByteBuffer bb = ByteBuffer.wrap(arg0.array()); WsOutbound wb = bmsg.getWsOutbound(); wb.writeBinaryMessage(bb); wb.flush(); } } /** * 字符处理 */ protected void onTextMessage(CharBuffer msg) throws IOException { logger.debug("onOpen(WsOutbound) this:" + msg); //$NON-NLS-1$ /*String msgStr = msg.toString(); JSONObject msgObject = JSONObject.fromObject(msg); String userId = msgObject.optString("sendTo"); String msgContent = msgObject.optString("content"); sendToUser(userId,msgContent);*/ for (WebSocketInboundImpl msgib : WebSocketService.getMessageInbound()) { CharBuffer cb = CharBuffer.wrap(msg); WsOutbound wb = msgib.getWsOutbound(); wb.writeTextMessage(cb); wb.flush(); } } public static void sendToUser(String toUserId,String msg) throws IOException { if (logger.isInfoEnabled()) { logger.info("sendToUser(String, String) - userId=" + toUserId + ", msg=" + msg); //$NON-NLS-1$ //$NON-NLS-2$ } for (WebSocketInboundImpl msgib : WebSocketService.getMessageInbound()) { String uid = msgib.getUserId(); if (logger.isInfoEnabled()) { logger.info("sendToUser(String, String) - String uid=" + uid); //$NON-NLS-1$ } if(!toUserId.equals(uid)){ continue; } WsOutbound wb = msgib.getWsOutbound(); CharBuffer cb = CharBuffer.wrap(msg); wb.writeTextMessage(cb); wb.flush(); } } public String getUserId() { return userId; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("WebSocketInboundImpl [userId=").append(userId) .append("]"); return builder.toString(); }
}
解决 无用评论 打赏 举报
悬赏问题
- ¥15 微信会员卡接入微信支付商户号收款
- ¥15 如何获取烟草零售终端数据
- ¥15 数学建模招标中位数问题
- ¥15 phython路径名过长报错 不知道什么问题
- ¥15 深度学习中模型转换该怎么实现
- ¥15 HLs设计手写数字识别程序编译通不过
- ¥15 Stata外部命令安装问题求帮助!
- ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
- ¥15 TYPCE母转母,插入认方向
- ¥15 如何用python向钉钉机器人发送可以放大的图片?