问题描述
- websocket移动端无效但是电脑端正常
-
用websocket做了个聊天功能,在电脑端可以正常使用。但在手机端却不能使用。就是在手机端登陆的时候获取不到用户的id.
解决方案
解决方案二:
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();
}
}
解决方案三:
楼主解决这个问题了吗。。。 我也遇到了。。。
时间: 2024-09-07 20:36:51