i'm trying to implement simple push notification based on socket.io, in my simple code to practice how can i do that i wrote simple code, in my code i can't send message to connected user , when use logged into system i store socket.io
with the key on redis
, but on send message to user i get key as username from redis and stored socket.io
value from redis and i'm trying to send, i get the same socket.io
value but message dont send to user
client side:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>
Document
</title>
</meta>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#login').click(function () {
socket.emit('login', {username: 'a', password: 'a'});
});
$('#mesage').click(function () {
socket.emit('message', 'a');
});
});
</script>
<script>
var socket = new io.connect('http://192.168.1.35:3000', {
port : 3000,
transports: ['websocket']
});
socket.on('connect', function () {
console.log('connected!');
});
socket.on('login', function (message) {
console.log(message);
});
socket.on('message', function (message) {
console.log(message);
});
socket.on('hello,', function (message) {
console.log(message);
});
socket.on('success', function (data) {
console.log(data);
});
</script>
</head>
<body>
<h3 id="login">
login
</h3>
<h3 id="mesage">
mesage
</h3>
</body>
</html>
server side:
var socket = require('socket.io'),
express = require('express'),
app = express(),
server = require('http').createServer(app),
io = socket.listen(server),
port = process.env.PORT || 3000,
redis = require("redis"),
redisClient = redis.createClient();
socket.on('connection', function (socket) {
socket.on('login', function (data) {
login(data.username, data.password, function (success, value) {
if (success) {
redisClient.exists(data.username, function (err, doesExist) {
if (err) return;
if (!doesExist) {
redisClient.set(data.username, socket.id);
}
else {
redisClient.del(data.username);
redisClient.set(data.username, socket.id);
}
log.info("SOCKET ID: " + socket.id);
});
socket.emit('login', {result: success, id: socket.id});
} else {
socket.emit('login', {result: false, id: socket.id});
}
});
});
socket.on('message', function (username) {
redisClient.get(username, function (err, socketId) {
if (err)
socket.emit('message', err);
io.to(socketid).emit('message', 'for your eyes only');
});
});
});
when i click on login
i get this result:
Object { result=true, id="/#A5sR-Xo-Owo97NvRAAAB"}
and when i click on message i get this result:
user not connected /#A5sR-Xo-Owo97NvRAAAB
both of socket.id
s are the same, but client dont get any message and server return this message as user not connected
See Question&Answers more detail:
os