node.js - 尝试向已通过用户身份验证的登录用户发送消息时出现问题
问题描述
我正在使用 node.js、ejs 和 socket.io。Mysql用于数据库。
我想达到什么目的?
假设有 2 个用户并且用户 2 已经登录。当用户 1 登录时,它会通知用户 2 用户 1 已登录。
到目前为止我尝试了什么?
下面是 jquery ajax 对数据库中用户进行身份验证的成功回调。
success: function(result) {
//Connnecting with socket.
var clientSocket = io().connect("http://localhost:1235?Token=" + result.Data.Token);
//Once connected, emit the message in success callback that User 1 is logged in.
//Then redirecting the user to profile page in the success callback of emit.
clientSocket.on("connect", function() {
clientSocket.emit("Profile", { "Message": "User is online." }, function(receipt) {
if(receipt) {
location.href = "/profile";
}
});
});
}
到目前为止,一切都很好。
下面是服务器端代码。
var socket_io = socket(server);
socket_io.on("connection", function(socketParam) {
console.log("Connected");
//Send Message to all users once the user is authenticated as requested in above ejs
socketParam.on("Profile", function(data, profileCallback) {
profileCallback(true);
console.log(data);
socket_io.emit("Profile", data);
});
});
问题现在从下面的代码开始。以下代码出现在配置文件页面中,一旦用户通过身份验证并被重定向到此页面,该页面就会出现。
var userData = JSON.parse(localStorage.getItem("User_Data"));
clientSocket = io().connect("http://localhost:1235?Token=" + userData.Token);
clientSocket.on("connect", function() {
clientSocket.on("Profile", function(data) {
debugger;
});
});
上面代码(profile.ejs)中的问题是,当我到达个人资料页面时,正在重新建立连接。这会断开用户并重新连接,我认为由于这个原因,从服务器发出的 Profile 事件中的数据永远不会到达。
问题 有什么方法可以保持在客户端建立的连接,这样就不需要重新建立连接?
如果您需要更多信息,请告诉我。
解决方案
推荐阅读
- json - jq 查询返回太多记录(不需要的排列)
- javascript - GLTF Loader 不工作且不加载 3D 模型
- regex - 如何在 vue-tel-input 中应用自定义验证
- sql - 如何让 LAG() 在 SQL Server 中忽略 NULLS?
- reactjs - this.refs x useRef(有什么相似之处吗?)
- powerbi - 如何使运行总计忽略其他列 DAX
- python - Python仅合并/追加新的excel文件
- ember.js - Ember Super Rentals 教程 3.15 - 处理数据
- javascript - 标识符“_toConsumableArray”已被声明
- python - 我无法在 osbrain 上创建分布式系统