我是使用ws-library创建nodejs-websocket服务器的。
我想在android中添加一个模块,用于与管理员聊天。
插座.js
const Messages = require('../models/index').Messages;
module.exports = (httpsServer) => {
const WebSocketServer = require('ws').Server;
const wss = new WebSocketServer({
server: httpsServer
});
wss.on('connection', function connection(ws) {
console.log('connected');
ws.on('message', function incoming(message) {
console.log('received: %s', message);
let jsonObject = JSON.parse(message);
switch (jsonObject.class) {
case "userIdFromUser":
Messages.findAll({
attributes: ['message', 'roomId', 'senderId', 'createdAt'],
where: {
roomId: jsonObject.data.senderId
},
order: [
['createdAt', 'ASC']
]
}).then(message => {
let response = {
"class": "getAllMessages",
"data": message
};
wss.clients.forEach(function each(client) {
if (client != ws) {
console.log('client opened');
client.send(JSON.stringify(response));
}
});
});
break;
case "messageToAdmin":
Messages.create({
roomId: jsonObject.data.senderId,
senderId: jsonObject.data.senderId,
message: jsonObject.data.message
}).then(message => {
let response = {
"class": "messageToUser",
"data": message
};
wss.clients.forEach(function each(client) {
if (client != ws) {
console.log('client opened');
client.send(JSON.stringify(response));
}
});
});
break;
case "messageToUser":
Messages.create({
roomId: jsonObject.data.senderId,
senderId: "1", //administrator
message: jsonObject.data.message
}).then(message => {
let response = {
"class": "messageToAdmin",
"data": message
};
wss.clients.forEach(function each(client) {
if (client != ws) {
console.log('client opened');
client.send(JSON.stringify(response));
}
});
});
break;
default:
break;
}
});
});
};
对于android,我使用okhttp、nkzawa/socket.io-client、nv-websocket-client、tootallnate/java-websocket库来连接websocket服务器。
所有库都在工作,但只针对单个用户。当我从第二个设备连接时,没有收到消息。当用户向管理员发送消息时,onmessage event not run。
从上面的库来看,okhttp更适合于连接和重新连接。我尝试为okhttp添加forcenewconnection(true),但是没有找到一个好的例子。
我怎样才能解决这个问题。谢谢你的建议。。。
暂无答案!
目前还没有任何答案,快来回答吧!