En başta istemci bacağında nasıl bir js dosyası çalışacak:
$(document).ready(function () { // connect to the socket server var socket = io.connect(); // if we get an "info" emit from the socket server then console.log the data we recive socket.on('info', function (data) { console.log("info client tarafı"); console.log(data); }); });
app.js içindeki kritik nokta:
/* SESSION Ayarları */ var session = require('express-session'); var RedisStore = require('connect-redis')(session); // Redis'te tutacağız var sessionMiddleware = session({ resave: true, saveUninitialized: true, store: new RedisStore({host: '127.0.0.1', port: 6379}), key: 'session_id_tutan_anahtar_kelimemiz', secret: 'sir_dolu_sozcugumuz_sifrelesin_deyyu' }); app.use(sessionMiddleware); // express session ayarlarımızı kullansın
bin/www dosyasındaki esas nokta socket oluşturma ve socket içindeki session bilgilerine erişmek:
/* SOCKET */ var session = require('express-session'); var RedisStore = require('connect-redis')(session); var sessionMiddleware = session({ resave: true, saveUninitialized: true, store: new RedisStore({host: '127.0.0.1', port: 6379}), key: 'express.sid', secret: 'secret' }); var arrSessions = []; var sio = require('socket.io').listen(server); sio.use(function(socket, next) { sessionMiddleware(socket.request, socket.request.res, next); }); sio.sockets.on('connection', function (socket) { console.log("-------------Session ID: "+socket.request.sessionID); console.log('A new user connected!'); arrSessions.push(socket.request.sessionID); console.log(arrSessions); socket.emit('info', { msg: 'The world is round, there is no up or down.' }); });
Ekran Çıktıları
Tüm Kod
app.js dosyası:var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var io = require('socket.io'); var routes = require('./routes/index'); var users = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(express.static(path.join(__dirname, 'public'))); app.use(cookieParser()); /* SESSION Ayarları */ var session = require('express-session'); var RedisStore = require('connect-redis')(session); // Redis'te tutacağız var sessionMiddleware = session({ resave: true, saveUninitialized: true, store: new RedisStore({host: '127.0.0.1', port: 6379}), key: 'session_id_tutan_anahtar_kelimemiz', secret: 'sir_dolu_sozcugumuz_sifrelesin_deyyu' }); app.use(sessionMiddleware); // express session ayarlarımızı kullansın /* GET home page. */ app.use('/', express.Router().get('/', function(req, res, next) { req.session.deneme = '^cem$'; res.render('index', { title: 'Express', sid:req.sessionID }); })); // catch 404 and forward to error handler app.use(function (req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); module.exports = app;
bin/www dosyasının içeriği
#!/usr/bin/env node /** * Module dependencies. */ var app = require('../app'); var debug = require('debug')('redis_pub_sub:server'); var http = require('http'); /** * Get port from environment and store in Express. */ var port = normalizePort(process.env.PORT || '3000'); app.set('port', port); /** * Create HTTP server. */ var server = http.createServer(app); /** * Listen on provided port, on all network interfaces. */ server.listen(port); server.on('error', onError); server.on('listening', onListening); /** * Normalize a port into a number, string, or false. */ function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } /** * Event listener for HTTP server "error" event. */ function onError(error) { if (error.syscall !== 'listen') { throw error; } var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } } /** * Event listener for HTTP server "listening" event. */ function onListening() { var addr = server.address(); var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; debug('Listening on ' + bind); } /* SOCKET */ var session = require('express-session'); var RedisStore = require('connect-redis')(session); var sessionMiddleware = session({ resave: true, saveUninitialized: true, store: new RedisStore({host: '127.0.0.1', port: 6379}), key: 'express.sid', secret: 'secret' }); var arrSessions = []; var sio = require('socket.io').listen(server); sio.use(function(socket, next) { sessionMiddleware(socket.request, socket.request.res, next); }); sio.sockets.on('connection', function (socket) { console.log("-------------Session ID: "+socket.request.sessionID); console.log('A new user connected!'); arrSessions.push(socket.request.sessionID); console.log(arrSessions); socket.emit('info', { msg: 'The world is round, there is no up or down.' }); }); //for testing, we're just going to send data to the client every second setInterval(function (socket) { /* our message we want to send to the client: in this case it's just a random number that we generate on the server */ var msg = Math.random(); sio.emit('info', msg); console.log(msg); }, 10000);
Kaynaklar: