Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket io connection from one page in Yii2

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.

like image 406
Dmytro Avatar asked Dec 18 '25 11:12

Dmytro


1 Answers

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.

like image 87
Dmytro Avatar answered Dec 20 '25 07:12

Dmytro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!