我正在尝试创建一个实时应用程序聊天,并且我想在其中有单独的组和渠道,例如Telegram和WhatsApp,我使用node js和socket.io来完成,但是当我这样做时,每条消息都会进来所有组并且确实存在冲突,如何实现它,我可以使用一个文件.js和一个套接字来完成它吗,例如以下代码?
const express = require('express'),
http = require('http'),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "TELETRAINING"
});
app.get('/', function (req, res) {
res.send('Chat Server is running on port 3000')
})
io.on('connection', function (socket) {
console.log('user connected')
socket.on('userisinchatroom', function (classid, userid) {
console.log("chat for classromm with id:" + classid)
var sql = "SELECT content FROM chat WHERE studentid=" + classid;
con.query(sql, function (err, result) {
if (err) throw err;
console.log("messages is forward to client!");
let query = {"messageList": result};
io.emit("query", query);
})
})
socket.on('join', function (userNickname) {
console.log(userNickname + " : has joined the chat ");
socket.broadcast.emit('userjoinedthechat', userNickname + " : has joined
the chat ");
})
socket.on('messagedetection', function (senderNickname, messageContent,
studentid, classid) {
//log the message in console
console.log(senderNickname + " : " + messageContent)
// con.connect(function (err) {
//if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO chat (content,studentid, classid) VALUES ('" + messageContent + "', '" + studentid + "', '" + classid + "')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted")
});
// con.end();
// });
//create a message object
let message = {"message": messageContent, "senderNickname": senderNickname}
// send the message to all users including the sender using io.emit()
io.socket().in(socket.id).emit('message', message)
})
socket.on('disconnect', function (userNickname) {
console.log(userNickname + ' has left ')
socket.broadcast.emit("userdisconnect", ' user has left')
})
})
server.listen(3000, function () {
console.log('Node app is running on port 3000')
})