39,087
社区成员
发帖
与我相关
我的任务
分享
var socket = new WebSocket('ws://'+window.location.host + rootPath +'/websocket');
socket.onopen = function(event){
console.log('step in onpen function);
console.log(event.data);
};
public void sendMsg(String msg) {
StreamInbound streamInbound = null;
//此处为错误代码,问题出现原因是在for循环外调用了wrap方法,结果在发送后buffer自动被清空
//但是不会引起程序的异常,所以看起来就像我提到的那个现象,略坑。。。
//CharBuffer buffer = CharBuffer.wrap(msg);
for(int i=0;i<streamInbounds.size();i++){
// streamInbounds记录的是当前进行连接的客户端个数
// 用以确保每个客户端都能接受服务器发送的消息
// 声明方式为 public static Vector<StreamInbound> streamInbounds = new Vector<StreamInbound>();
streamInbound = streamInbounds.get(i);
try {
// 将wrap方法移动到for循环内,每次都重新进行赋值,问题解决
CharBuffer buffer = CharBuffer.wrap(msg);
streamInbound.getWsOutbound().writeTextMessage(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
再次感谢版主xmt1139057136