I am using Yii advanced project with socket io and nodejs. My server.js is located in yii2advanced/nodejs.
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
var connectedUsers = {};
server.listen(8890);
io.of('frontend/views/project/index').on('connection', function (socket) {
socket.on('usersocket', function(data) {
connectedUsers[data] = socket;
console.log("new client with Id: " + data + " added to CLIENTS list");
});
});
My client.js is located in yii2advanced/frontend/web/js.
$( document ).ready(function() {
var socket = io.connect('http://localhost:8890/frontend/views/project/index');
socket.on('connect', function () {
socket.emit('usersocket', user_id);
});
I need to allow socket to connect only from frontend/views/project/index.php page. Now socket connects even from frontend/web/index.php I followed an example from socket docs ('Restricting yourself to a namespace') but I am not sure if I specify the namespaces correctly.
I have solved this issue as following.
I created new layout project_layout for my project/index action (before all code in this action I wrote $this->layout = 'project_layout';).
I created new AssetBundle (ProjectAsset). Inside this Asset I wrote:
public $js = ['js/client.js'];
Inside new layout I registered new ProjectAsset:
use frontend\assets\ProjectAsset;
ProjectAsset::register($this);
So an idea is to use client.js only on page you need. Before this changes I had only one main layout for all actions. Thus on each page I had an AppAsset with client.js attached. Now it is attached only on project/index page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With