我使用ws库创建了nodejs WebSocket服务器。
我想向Android添加一个模块以便与管理员聊天。
socket.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事件不会运行。
从上述库中,okhttp更好地用于连接和重新连接。我试图为okhttp添加forceNewConnection(true),但没有找到一个很好的例子。
我该如何解决问题。感谢您的建议...