我正在android中使用socket.io开发一个一对一的聊天应用程序。我可以从一个聊天室发送和接收消息。我正在关注this tutorial 。我的应用程序聊天模块看起来像 that 。现在,我想从单个用户发送和接收消息。
在开发过程中,我观察到每个套接字连接,socket.io 都会为客户端提供一个新的 ID,如下所示:
/#IyQ7LaKzLClf7g3DAAAA
因此,我无法跟踪发送消息的特定用户。
问题 1. 我是否必须连接任何数据库来存储用户凭据才能向特定用户发送消息以及向他/她发送离线消息?聊天功能是我的 Android 应用程序中的附加功能。目前此应用程序使用基于 token 的身份验证。
我是 Node js 和 socket.io 的新手。给我一个如何解决这个问题的架构指南。 TIA。
我的 app.js 代码:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
// Routing
app.use(express.static(__dirname + '/public'));
// Chatroom
var numUsers = 0;
var clients = [];
io.on('connection', function (socket) {
var addedUser = false;
clients.push(socket);
console.log('one user connected: user name: ' +socket.username +"------ id : >> "+ socket.id);
console.log('Total User List:' + clients);
socket.on('connect', function (data) {
// we tell the client to execute 'new message'
socket.broadcast.emit('connect', {
username: socket.username,
numUsers: numUsers,
socket_id:socket.id
});
});
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
socket.broadcast.emit('new message', {
username: socket.username,
message: data
});
});
// when the client emits 'add user', this listens and executes
socket.on('add user', function (username) {
if (addedUser) return;
// we store the username in the socket session for this client
socket.username = username;
++numUsers;
addedUser = true;
socket.emit('login', {
numUsers: numUsers
});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username,
numUsers: numUsers,
socket_id:socket.id
});
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', function () {
socket.broadcast.emit('typing', {
username: socket.username
});
});
// when the client emits 'stop typing', we broadcast it to others
socket.on('stop typing', function () {
socket.broadcast.emit('stop typing', {
username: socket.username
});
});
// when want to send message to specific user
socket.on('say to someone', function (id, msg) {
socket.broadcast.to(id).emit('say to someone', {
username: socket.username,
id:id,
message: msg
});
});
// when the user disconnects.. perform this
socket.on('disconnect', function () {
clients.splice(clients.indexOf(socket), 1);
console.log('Disconnected... ' + socket.id);
if (addedUser) {
--numUsers;
// echo globally that this client has left
socket.broadcast.emit('user left', {
username: socket.username,
numUsers: numUsers
});
}
});
});
最佳答案
您的 socket.on('say to someone', function (id, msg)
请查看下面的链接
关于android - 在android中使用socket io进行身份验证以用于聊天应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37851017/