我正在为我的 php 应用程序中的实时私人消息传递系统工作。我的代码适用于所有用户。但我需要私人消息系统作为一对一消息。
在设置节点和redis之后,我可以获得我需要的消息数据:这是代码::
前端 :: 1. 我使用了一个表单——用户名、消息和发送按钮
和通知 JS:
$( document ).ready(function() {
var socket = io.connect('http://192.168.2.111:8890');
socket.on('notification', function (data) {
var message = JSON.parse(data);
$( "#notifications" ).prepend("<p> <strong> " + message.user_name + "</strong>: " + message.message + "</p>" );
});
});
服务器端js:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(8890);
var users = {};
var sockets = {};
io.on('connection', function (socket) {
console.log(" New User Connected ");
// instance of Redis Client
var redisClient = redis.createClient();
redisClient.subscribe('notification');
socket.on('set nickname', function (name) {
socket.set('nickname', name, function () {
socket.emit('ready');
});
});
socket.on('msg', function () {
socket.get('nickname', function (err, name) {
console.log('Chat message by ', name);
});
});
redisClient.on("message", function(channel, message)
{
// to view into terminal for monitoring
console.log("Message from: " + message + ". In channel: " + channel + ". Socket ID "+ socket.id );
//send to socket
socket.emit(channel, message);
});
redisClient.on('update_chatter_count', function(data)
{
socket.emit('count_chatters', data);
});
//close redis
socket.on('disconnect', function()
{
redisClient.quit();
});
});
HTML::
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<form .....>
<input ....... >
</form>
<div id="notifications" ></div>
总输出:
John : Hello
Kate : Hi
Others: .....
以上代码在我的 php 应用程序中运行良好。现在我想建立私人或一对一的消息系统。
我需要为用户添加用户名或电子邮件或唯一 socketID 的方式。我对私人消息没有更多的想法。我试图在网上计算,但失败了。
**如何在我的 php 应用程序中设置私人消息?**