因此,我目前使用 Node 和 socket.io
启动并运行了一个实时聊天应用程序。我想做的是让用户创建一个帐户并根据用户名搜索其他用户。然后,他们可以通过请求将他们添加为 friend 以开始聊天。
我浏览过网络试图回答这个问题,但找不到任何可靠的起点。我是 node.js
、express
和 socket.io
的新手,并且希望获得有关此问题的帮助。
如果您能为我指明如何使用 Node 创建基于 friend 的系统的正确方向,那就太棒了。谢谢!
最佳答案
我也认为这是一个广泛的问题,但我会尽力让您了解您正在尝试做的事情的技术方面。
首先,你应该有一个用户管理系统,包括登录、注册、忘记密码等。你可以使用 passport.js为了这。现在,您已经拥有了完整的用户管理系统,您可以进一步开始。
如果您愿意最终控制聊天系统的好友请求/接受功能,您可能想要创建如下所示的数据库结构。
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
// Schema defines how chat messages will be stored in MongoDB
const FriendsSchema = new Schema({
participants: [{ type: Schema.Types.ObjectId, ref: 'user' }],
requestTo: {type: Schema.Types.ObjectId, ref: 'user'},
accepted: {tyoe: Boolen, default:false}
});
module.exports = mongoose.model('Friends', FriendsSchema);
您可以检查此数据库以创建友谊请求,检查两个用户之间的友谊等。您应该在数据库中做的另一件事是创建聊天模型。保存消息,如下所示:
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
const MessageSchema = new Schema({
friendshipId: {
type: Schema.Types.ObjectId,
required: true,
ref: 'Friends'
},
body: {
type: String,
required: true
},
author: {
type: Schema.Types.ObjectId,
ref: 'user'
},
seen: {
type: Boolean,
default: false
},
delivered: {
type: Boolean,
default: false
}
},
{
timestamps: true // Saves createdAt and updatedAt as dates. createdAt will be our timestamp.
});
module.exports = mongoose.model('Message', MessageSchema);
现在,对于实时聊天系统,您应该集成socket.io 和数据库。您可以像下面的代码一样进行操作。
var http = require('http')
var redis = require('redis')
var client = redis.createClient()
module.exports = (app) => {
const server = http.createServer(app)
const io = require('socket.io').listen(server)
io.sockets.on('connection', (socket) => {
socket.on('sendChat', (user, msg, messageId) => {
client.get(user, function(err, socketId){
io.to(socketId).emit('updateChat', socket.username, msg, messageId)
})
})
socket.on('delivered', (user, messageId) => {
client.get(user, function(err, socketId){
io.to(socketId).emit('delivered', messageId)
})
})
socket.on('seen', (user, messageId) => {
client.get(user, function(err, socketId){
io.to(socketId).emit('seen', messageId)
})
})
socket.on('adduser', (username) => {
client.set(username, socket.id, function(err){
socket.username = username
io.sockets.emit('updateOnlineUser', username)
})
})
socket.on('disconnect', function(){
client.del(socket.username)
io.sockets.emit('updateOfflineUser', socket.username)
})
})
}
上面发生了什么?它基本上创建到客户端的连接,当客户端向服务器发送 addUser 事件时,它将用户存储在 radis 存储中。当通过套接字传输消息时,通过发送 sendChat 事件,将事件发送给另一个聊天用户。您还需要将此聊天记录保存到数据库中。
当用户不想向未通过套接字连接的非事件用户发送消息时。您必须实现消息传递任务的端点。欲了解更多信息请关注this open source project .
关于javascript - Node.js 中基于好友的系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43381834/