Comments (12)
- как считаете коннекты?
- 'master' - используется для соединения с другим процессом посредством сокета в текстовом формате, в Chat2 можно посмотреть пример реализации.
from websocket.
Считается, дак просто, count($this->userIds).
from websocket.
у меня не было такого кода в примере.
покажите ваш модифицированный код
from websocket.
Handle:
protected function onServiceMessage($connectionId, $data)
{
$data = json_decode($data);
$message = @$data->message;
$action = @$data->action;
$toUser = @$data->userId;
if( $action )
{
if( 'readNewMsg'==$action )
{
$send = "no";
$message = $action;
foreach( $this->userIds as $clientId => $userId )
{
if( $toUser == $userId )
{
$send = "ok";
$this->sendToClient($clientId,$message);
}
}
$this->sendToService($connectionId,json_encode(array('send' => $send)));
}
if( 'pingUser'==$action )
{
$online = FALSE;
foreach( $this->userIds as $clientId => $userId )
{
if( $toUser == $userId ) $online = TRUE;
}
$this->sendToService($connectionId,json_encode(array('online' => $online)));
}
if( 'countUsers'==$action )
{
$msg = NULL;
if( 'full'==$toUser ) $msg = json_encode(array('count' => count($this->userIds),'users' => $this->userIds));
elseif( 'count'==$toUser ) $msg = count($this->userIds);
elseif( 'list'==$toUser ) $msg = json_encode($this->userIds);
$this->sendToService($connectionId,$msg);
}
}
else foreach( $this->userIds as $clientId => $userId ) if( $toUser == $userId ) $this->sendToClient($clientId,$message);
}
В момент же открытия:
protected function onOpen($connectionId, $info) /// Вызывается при соединении с новым клиентом
{
///$message = 'пользователь #' . $connectionId . ' : ' . var_export($info, true) . ' ' . stream_socket_get_name($this->clients[$connectionId], true);
///foreach( $this->clients as $clientId => $client ) $this->sendToClient($clientId, $message);
$info['GET']; /// or use $info['Cookie'] for use PHPSESSID or $info['X-Real-IP'] if you use proxy-server like nginx
parse_str(substr($info['GET'], 1), $_GET);//parse get-query
///var_export($_GET['id']);
$userId = @$_GET['userId'];
$this->userIds[$connectionId] = $userId;
}
Дак вот, просто считаю $this->userIds или неправильно?
from websocket.
Да вроде правильно, а этот код я надеюсь не удалялся?
protected function onClose($connectionId) {//it is called when existed connection is closed
unset($this->userIds[$connectionId]);
}
from websocket.
На месте)).
Ну значит живые получается.
На текущий момент уже 6188 !!
from websocket.
а какая дневная посещаемость сайта (сколько уникальных пользователей в день), что столько соединений?
from websocket.
Здравствуйте. Постоянно наблюдаю активные соединения, если было прерывание интернета или если браузер грохнуть в диспетчере задач. Проблему решил посыланием пинга и ожиданием понга по таймеру. если ответ не пришел, убиваю соединение
from websocket.
@olegius88
Если не затруднит, поделитесь скриптиком.
Спасибо
from websocket.
@olegius88
Что вы подразумеваете под словом посылает пинг?
Есть какой то метод?
Или просто маленькое сообщение вы так обозначили?
from websocket.
@morozovsk
Может вы прокомментируете?
from websocket.
Спасибо! Все рабоатет!
from websocket.
Related Issues (20)
- Как подружить с pg_notify HOT 4
- GenericEvent считывает не весь буфер HOT 2
- список онлайн юзеров HOT 8
- Отправка изображения через вебсокет
- Работа в Safari HOT 1
- wss timeot HOT 17
- stream_select(): supplied argument is not a valid stream resource HOT 7
- Не закрывает соединение при окончании на сайте HOT 4
- Как сделать многопоточность? HOT 6
- request response order HOT 1
- Можно ли создавать комнаты? HOT 12
- PHP Client HOT 3
- Один конект по сокету на несколько вкладок HOT 2
- Потраченное время на разработку. HOT 4
- "Залипает" при слишком длинном handshake-сообщение (режим event) HOT 4
- websocket lunch on remote host HOT 1
- Ошибка при остановке HOT 2
- Каково потребление памяти и cpu при нагрузке в 100 000 соединений? HOT 4
- Почему бросили? HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from websocket.