[+] реализация чата на сокетах (работает)
This commit is contained in:
1 parent
6960cb17b1
commit
de5a1d6e7c
5 files changed
+633
-103
No files matched your search
+133
@@ -40,6 +40,139 @@
|
||||
|
||||
|
||||
типа статистика или хз
|
||||
|
||||
<p id="userList"></p>
|
||||
<p id="app"></p>
|
||||
<input id="message" type="text">
|
||||
<button id="sendBtn">send</button>
|
||||
|
||||
|
||||
|
||||
<script>
|
||||
let socket = new WebSocket('wss://dev.it-stories.ru/wss?userName=<?= $USER->getLogin()?>');
|
||||
|
||||
socket.onopen = function(e) {
|
||||
/*const initMessage = {
|
||||
method: 'registration',
|
||||
userId: <?= $USER->getId() ?>,
|
||||
date: Date.now()
|
||||
};
|
||||
socket.send(JSON.stringify(initMessage));*/
|
||||
};
|
||||
|
||||
socket.onmessage = function(event) {
|
||||
let data = JSON.parse(event.data);
|
||||
|
||||
|
||||
|
||||
|
||||
// Обработка пингов
|
||||
if (data.action === 'Ping') {
|
||||
const pongMessage = {action: 'Pong'};
|
||||
socket.send(JSON.stringify(pongMessage));
|
||||
return;
|
||||
}
|
||||
|
||||
// Обработка подключившихся пользователей
|
||||
if (data.action === 'PublicMessage') {
|
||||
$('#app').append(`<div class="messageBox"><div class="userLogin">${data.userName}</div><div class="message">${data.text}</div></div>`)
|
||||
return;
|
||||
}
|
||||
|
||||
// Обработка при подключении
|
||||
if (data.action === 'Connected') {
|
||||
$('#app').append(`<div class="messageBox"><div class="notification">Пользователь ${data.userName} подлючился в чат</div></div>`)
|
||||
//return;
|
||||
}
|
||||
|
||||
// Обработка при подключении
|
||||
if (data.action === 'Authorized') {
|
||||
$('#userList').html('');
|
||||
data.users.forEach(function(element){
|
||||
$('#userList').append(`<div class="userElement">${element.userName}</div>`)
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Обработка при отклбчении
|
||||
if (data.action === 'Disconnected') {
|
||||
$('#app').append(`<div class="messageBox"><div class="notification">Пользователь ${data.userName} покинул чат</div></div>`)
|
||||
|
||||
$('#userList').html('');
|
||||
data.users.forEach(function(element){
|
||||
$('#userList').append(`<div class="userElement">${element.userName}</div>`)
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
|
||||
console.log('Данные получены с сервера: ' + JSON.stringify(data))
|
||||
|
||||
|
||||
|
||||
//$('#app').append(`<div class="messageBox"><div class="userLogin">${data.userName}</div><div class="message">${data.text}</div></div>`)
|
||||
|
||||
|
||||
$('#app').html($('#app').html() + "<br>" + event.data);
|
||||
};
|
||||
|
||||
socket.onclose = function(event) {
|
||||
if (event.wasClean) {
|
||||
console.log(`[close] Соединение закрыто чисто, код=${event.code} причина=${event.reason}`);
|
||||
} else {
|
||||
// например, сервер убил процесс или сеть недоступна
|
||||
// обычно в этом случае event.code 1006
|
||||
console.log('[close] Соединение прервано');
|
||||
}
|
||||
};
|
||||
|
||||
socket.onerror = function(error) {
|
||||
console.log(`[error]`);
|
||||
};
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
<script>
|
||||
$('#sendBtn').on('click', function(){
|
||||
const message = {
|
||||
action: 'PublicMessage',
|
||||
text: $('#message').val()
|
||||
};
|
||||
socket.send(JSON.stringify(message));
|
||||
$('#message').val('');
|
||||
});
|
||||
</script>
|
||||
<style>
|
||||
.messageBox {
|
||||
border: 1px solid #dbdbdb;
|
||||
margin: 5px;
|
||||
padding: 5px;
|
||||
background: #f9f9f9;
|
||||
}
|
||||
.userLogin {
|
||||
font-weight: bold;
|
||||
color: green;
|
||||
}
|
||||
|
||||
.notification {
|
||||
font-style: italic;
|
||||
color: #e50000;
|
||||
}
|
||||
|
||||
p#userList {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.userElement {
|
||||
border: 1px solid #687cff;
|
||||
margin: 2px;
|
||||
padding: 5px;
|
||||
background: blue;
|
||||
color: white;
|
||||
}
|
||||
</style>
|
||||
</div><!-- contentpanel -->
|
||||
<?php
|
||||
require_once __DIR__ . '/inc/footer.php';
|
||||
@@ -0,0 +1,158 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<!-- Required meta tags -->
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
|
||||
<!-- Bootstrap CSS -->
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
|
||||
|
||||
<title>Чат для компании</title>
|
||||
<style>
|
||||
div#app {
|
||||
height: 380px;
|
||||
overflow-y: scroll;
|
||||
box-shadow: inset 0px 15px 10px -7px black;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="container mt-5">
|
||||
|
||||
<div id="userList"></div>
|
||||
|
||||
|
||||
<div id="app">
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
<div class="input-group">
|
||||
<div class="input-group-prepend">
|
||||
<span class="input-group-text">Введите сообщение</span>
|
||||
</div>
|
||||
<textarea id="message" class="form-control" aria-label="With textarea"></textarea>
|
||||
</div>
|
||||
<button id="sendBtn" type="button" class="btn btn-primary btn-lg btn-block">Отправить</button>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
|
||||
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
|
||||
|
||||
<script>
|
||||
function getRandomInt(min, max) {
|
||||
min = Math.ceil(min);
|
||||
max = Math.floor(max);
|
||||
return Math.floor(Math.random() * (max - min)) + min;
|
||||
}
|
||||
|
||||
let socket = new WebSocket('wss://dev.it-stories.ru/wss?userName=Guest_' + getRandomInt(1, 9999));
|
||||
|
||||
socket.onopen = function(e) {
|
||||
/*const initMessage = {
|
||||
method: 'registration',
|
||||
userId: 1,
|
||||
date: Date.now()
|
||||
};
|
||||
socket.send(JSON.stringify(initMessage));*/
|
||||
};
|
||||
|
||||
socket.onmessage = function(event) {
|
||||
let data = JSON.parse(event.data);
|
||||
// Обработка пингов
|
||||
if (data.action === 'Ping') {
|
||||
const pongMessage = {action: 'Pong'};
|
||||
socket.send(JSON.stringify(pongMessage));
|
||||
return;
|
||||
}
|
||||
|
||||
// Обработка подключившихся пользователей
|
||||
if (data.action === 'PublicMessage') {
|
||||
$('#app').append(`<div class="alert alert-success" role="alert"><h5 class="alert-heading" onClick="contactTo('${data.userName}')">${data.userName}</h5>${data.text}</div>`)
|
||||
//return;
|
||||
}
|
||||
|
||||
// Обработка при подключении
|
||||
if (data.action === 'Connected') {
|
||||
$('#app').append(`<div class="alert alert-info" role="alert">Пользователь <b>${data.userName}</b> подлючился в чат</div>`)
|
||||
//return;
|
||||
}
|
||||
|
||||
// Обработка при подключении
|
||||
if (data.action === 'Authorized') {
|
||||
$('#userList').html('');
|
||||
data.users.forEach(function(element){
|
||||
$('#userList').append(`<span class="badge badge-secondary m-2">${element.userName}</span>`)
|
||||
});
|
||||
//return;
|
||||
}
|
||||
|
||||
// Обработка при отклбчении
|
||||
if (data.action === 'Disconnected') {
|
||||
$('#app').append(`<div class="alert alert-info" role="alert">Пользователь <b>${data.userName}</b> покинул чат</div>`)
|
||||
|
||||
$('#userList').html('');
|
||||
data.users.forEach(function(element){
|
||||
$('#userList').append(`<span class="badge badge-secondary">${element.userName}</span>`)
|
||||
});
|
||||
//return;
|
||||
}
|
||||
|
||||
// Обработка при отклбчении
|
||||
if (data.action === 'Information') {
|
||||
$('#app').append(`<div class="alert alert-warning" role="alert">${data.text}</div>`)
|
||||
//return;
|
||||
}
|
||||
|
||||
window.document.getElementById('app').scrollTop = window.document.getElementById('app').scrollHeight
|
||||
};
|
||||
|
||||
socket.onclose = function(event) {
|
||||
if (event.wasClean) {
|
||||
console.log(`[close] Соединение закрыто чисто, код=${event.code} причина=${event.reason}`);
|
||||
} else {
|
||||
console.log('[close] Соединение прервано');
|
||||
}
|
||||
};
|
||||
|
||||
socket.onerror = function(error) {
|
||||
console.log(`[error]`);
|
||||
};
|
||||
|
||||
$('#sendBtn').on('click', function(){
|
||||
let messageText = $('#message').val();
|
||||
if (messageText === "") {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = {
|
||||
action: 'PublicMessage',
|
||||
text: $('#message').val()
|
||||
};
|
||||
socket.send(JSON.stringify(message));
|
||||
$('#message').val('');
|
||||
});
|
||||
|
||||
function contactTo(name){
|
||||
$('#message').val($('#message').val() + " [b]" + name + "[/b] ");
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
</body>
|
||||
</html>
|
||||
Generated
+99
-99
@@ -1473,16 +1473,16 @@
|
||||
},
|
||||
{
|
||||
"name": "sentry/sentry",
|
||||
"version": "3.11.0",
|
||||
"version": "3.13.1",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/getsentry/sentry-php.git",
|
||||
"reference": "91bd6e54d9352754bbdd1d800d2b88618f8130d4"
|
||||
"reference": "71c86fe4699a7f1a40c7d985f3dc7667045152f0"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/getsentry/sentry-php/zipball/91bd6e54d9352754bbdd1d800d2b88618f8130d4",
|
||||
"reference": "91bd6e54d9352754bbdd1d800d2b88618f8130d4",
|
||||
"url": "https://api.github.com/repos/getsentry/sentry-php/zipball/71c86fe4699a7f1a40c7d985f3dc7667045152f0",
|
||||
"reference": "71c86fe4699a7f1a40c7d985f3dc7667045152f0",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -1494,7 +1494,7 @@
|
||||
"php": "^7.2|^8.0",
|
||||
"php-http/async-client-implementation": "^1.0",
|
||||
"php-http/client-common": "^1.5|^2.0",
|
||||
"php-http/discovery": "^1.11",
|
||||
"php-http/discovery": "^1.11, <1.15",
|
||||
"php-http/httplug": "^1.1|^2.0",
|
||||
"php-http/message": "^1.5",
|
||||
"psr/http-factory": "^1.0",
|
||||
@@ -1527,7 +1527,7 @@
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "3.11.x-dev"
|
||||
"dev-master": "3.13.x-dev"
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
@@ -1561,7 +1561,7 @@
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/getsentry/sentry-php/issues",
|
||||
"source": "https://github.com/getsentry/sentry-php/tree/3.11.0"
|
||||
"source": "https://github.com/getsentry/sentry-php/tree/3.13.1"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -1573,7 +1573,7 @@
|
||||
"type": "custom"
|
||||
}
|
||||
],
|
||||
"time": "2022-10-25T14:36:50+00:00"
|
||||
"time": "2023-02-10T10:17:57+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/deprecation-contracts",
|
||||
@@ -1644,16 +1644,16 @@
|
||||
},
|
||||
{
|
||||
"name": "symfony/http-client",
|
||||
"version": "v5.4.15",
|
||||
"version": "v5.4.21",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/http-client.git",
|
||||
"reference": "8f29b0f06c9ff48c8431e78eb90c8bd6f82cb12b"
|
||||
"reference": "6b88914a7f1bf144df15904f60a19be78a67a3b2"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/http-client/zipball/8f29b0f06c9ff48c8431e78eb90c8bd6f82cb12b",
|
||||
"reference": "8f29b0f06c9ff48c8431e78eb90c8bd6f82cb12b",
|
||||
"url": "https://api.github.com/repos/symfony/http-client/zipball/6b88914a7f1bf144df15904f60a19be78a67a3b2",
|
||||
"reference": "6b88914a7f1bf144df15904f60a19be78a67a3b2",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -1711,7 +1711,7 @@
|
||||
"description": "Provides powerful methods to fetch HTTP resources synchronously or asynchronously",
|
||||
"homepage": "https://symfony.com",
|
||||
"support": {
|
||||
"source": "https://github.com/symfony/http-client/tree/v5.4.15"
|
||||
"source": "https://github.com/symfony/http-client/tree/v5.4.21"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -1727,7 +1727,7 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2022-10-25T16:22:13+00:00"
|
||||
"time": "2023-02-17T21:35:35+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/http-client-contracts",
|
||||
@@ -1809,16 +1809,16 @@
|
||||
},
|
||||
{
|
||||
"name": "symfony/options-resolver",
|
||||
"version": "v5.4.11",
|
||||
"version": "v5.4.21",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/options-resolver.git",
|
||||
"reference": "54f14e36aa73cb8f7261d7686691fd4d75ea2690"
|
||||
"reference": "4fe5cf6ede71096839f0e4b4444d65dd3a7c1eb9"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/options-resolver/zipball/54f14e36aa73cb8f7261d7686691fd4d75ea2690",
|
||||
"reference": "54f14e36aa73cb8f7261d7686691fd4d75ea2690",
|
||||
"url": "https://api.github.com/repos/symfony/options-resolver/zipball/4fe5cf6ede71096839f0e4b4444d65dd3a7c1eb9",
|
||||
"reference": "4fe5cf6ede71096839f0e4b4444d65dd3a7c1eb9",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -1858,7 +1858,7 @@
|
||||
"options"
|
||||
],
|
||||
"support": {
|
||||
"source": "https://github.com/symfony/options-resolver/tree/v5.4.11"
|
||||
"source": "https://github.com/symfony/options-resolver/tree/v5.4.21"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -1874,20 +1874,20 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2022-07-20T13:00:38+00:00"
|
||||
"time": "2023-02-14T08:03:56+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/polyfill-ctype",
|
||||
"version": "v1.26.0",
|
||||
"version": "v1.27.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/polyfill-ctype.git",
|
||||
"reference": "6fd1b9a79f6e3cf65f9e679b23af304cd9e010d4"
|
||||
"reference": "5bbc823adecdae860bb64756d639ecfec17b050a"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/6fd1b9a79f6e3cf65f9e679b23af304cd9e010d4",
|
||||
"reference": "6fd1b9a79f6e3cf65f9e679b23af304cd9e010d4",
|
||||
"url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/5bbc823adecdae860bb64756d639ecfec17b050a",
|
||||
"reference": "5bbc823adecdae860bb64756d639ecfec17b050a",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -1902,7 +1902,7 @@
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-main": "1.26-dev"
|
||||
"dev-main": "1.27-dev"
|
||||
},
|
||||
"thanks": {
|
||||
"name": "symfony/polyfill",
|
||||
@@ -1940,7 +1940,7 @@
|
||||
"portable"
|
||||
],
|
||||
"support": {
|
||||
"source": "https://github.com/symfony/polyfill-ctype/tree/v1.26.0"
|
||||
"source": "https://github.com/symfony/polyfill-ctype/tree/v1.27.0"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -1956,20 +1956,20 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2022-05-24T11:49:31+00:00"
|
||||
"time": "2022-11-03T14:55:06+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/polyfill-mbstring",
|
||||
"version": "v1.26.0",
|
||||
"version": "v1.27.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/polyfill-mbstring.git",
|
||||
"reference": "9344f9cb97f3b19424af1a21a3b0e75b0a7d8d7e"
|
||||
"reference": "8ad114f6b39e2c98a8b0e3bd907732c207c2b534"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/9344f9cb97f3b19424af1a21a3b0e75b0a7d8d7e",
|
||||
"reference": "9344f9cb97f3b19424af1a21a3b0e75b0a7d8d7e",
|
||||
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/8ad114f6b39e2c98a8b0e3bd907732c207c2b534",
|
||||
"reference": "8ad114f6b39e2c98a8b0e3bd907732c207c2b534",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -1984,7 +1984,7 @@
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-main": "1.26-dev"
|
||||
"dev-main": "1.27-dev"
|
||||
},
|
||||
"thanks": {
|
||||
"name": "symfony/polyfill",
|
||||
@@ -2023,7 +2023,7 @@
|
||||
"shim"
|
||||
],
|
||||
"support": {
|
||||
"source": "https://github.com/symfony/polyfill-mbstring/tree/v1.26.0"
|
||||
"source": "https://github.com/symfony/polyfill-mbstring/tree/v1.27.0"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -2039,20 +2039,20 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2022-05-24T11:49:31+00:00"
|
||||
"time": "2022-11-03T14:55:06+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/polyfill-php73",
|
||||
"version": "v1.26.0",
|
||||
"version": "v1.27.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/polyfill-php73.git",
|
||||
"reference": "e440d35fa0286f77fb45b79a03fedbeda9307e85"
|
||||
"reference": "9e8ecb5f92152187c4799efd3c96b78ccab18ff9"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/polyfill-php73/zipball/e440d35fa0286f77fb45b79a03fedbeda9307e85",
|
||||
"reference": "e440d35fa0286f77fb45b79a03fedbeda9307e85",
|
||||
"url": "https://api.github.com/repos/symfony/polyfill-php73/zipball/9e8ecb5f92152187c4799efd3c96b78ccab18ff9",
|
||||
"reference": "9e8ecb5f92152187c4799efd3c96b78ccab18ff9",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -2061,7 +2061,7 @@
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-main": "1.26-dev"
|
||||
"dev-main": "1.27-dev"
|
||||
},
|
||||
"thanks": {
|
||||
"name": "symfony/polyfill",
|
||||
@@ -2102,7 +2102,7 @@
|
||||
"shim"
|
||||
],
|
||||
"support": {
|
||||
"source": "https://github.com/symfony/polyfill-php73/tree/v1.26.0"
|
||||
"source": "https://github.com/symfony/polyfill-php73/tree/v1.27.0"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -2118,20 +2118,20 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2022-05-24T11:49:31+00:00"
|
||||
"time": "2022-11-03T14:55:06+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/polyfill-php80",
|
||||
"version": "v1.26.0",
|
||||
"version": "v1.27.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/polyfill-php80.git",
|
||||
"reference": "cfa0ae98841b9e461207c13ab093d76b0fa7bace"
|
||||
"reference": "7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/cfa0ae98841b9e461207c13ab093d76b0fa7bace",
|
||||
"reference": "cfa0ae98841b9e461207c13ab093d76b0fa7bace",
|
||||
"url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936",
|
||||
"reference": "7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -2140,7 +2140,7 @@
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-main": "1.26-dev"
|
||||
"dev-main": "1.27-dev"
|
||||
},
|
||||
"thanks": {
|
||||
"name": "symfony/polyfill",
|
||||
@@ -2185,7 +2185,7 @@
|
||||
"shim"
|
||||
],
|
||||
"support": {
|
||||
"source": "https://github.com/symfony/polyfill-php80/tree/v1.26.0"
|
||||
"source": "https://github.com/symfony/polyfill-php80/tree/v1.27.0"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -2201,7 +2201,7 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2022-05-10T07:21:04+00:00"
|
||||
"time": "2022-11-03T14:55:06+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/service-contracts",
|
||||
@@ -2288,16 +2288,16 @@
|
||||
},
|
||||
{
|
||||
"name": "twig/twig",
|
||||
"version": "v3.4.3",
|
||||
"version": "v3.5.1",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/twigphp/Twig.git",
|
||||
"reference": "c38fd6b0b7f370c198db91ffd02e23b517426b58"
|
||||
"reference": "a6e0510cc793912b451fd40ab983a1d28f611c15"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/twigphp/Twig/zipball/c38fd6b0b7f370c198db91ffd02e23b517426b58",
|
||||
"reference": "c38fd6b0b7f370c198db91ffd02e23b517426b58",
|
||||
"url": "https://api.github.com/repos/twigphp/Twig/zipball/a6e0510cc793912b451fd40ab983a1d28f611c15",
|
||||
"reference": "a6e0510cc793912b451fd40ab983a1d28f611c15",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -2312,7 +2312,7 @@
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "3.4-dev"
|
||||
"dev-master": "3.5-dev"
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
@@ -2348,7 +2348,7 @@
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/twigphp/Twig/issues",
|
||||
"source": "https://github.com/twigphp/Twig/tree/v3.4.3"
|
||||
"source": "https://github.com/twigphp/Twig/tree/v3.5.1"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -2360,7 +2360,7 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2022-09-28T08:42:51+00:00"
|
||||
"time": "2023-02-08T07:49:20+00:00"
|
||||
},
|
||||
{
|
||||
"name": "workerman/workerman",
|
||||
@@ -2668,16 +2668,16 @@
|
||||
},
|
||||
{
|
||||
"name": "composer/pcre",
|
||||
"version": "3.0.2",
|
||||
"version": "3.1.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/composer/pcre.git",
|
||||
"reference": "4482b6409ca6bfc2af043a5711cd21ac3e7a8dfb"
|
||||
"reference": "4bff79ddd77851fe3cdd11616ed3f92841ba5bd2"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/composer/pcre/zipball/4482b6409ca6bfc2af043a5711cd21ac3e7a8dfb",
|
||||
"reference": "4482b6409ca6bfc2af043a5711cd21ac3e7a8dfb",
|
||||
"url": "https://api.github.com/repos/composer/pcre/zipball/4bff79ddd77851fe3cdd11616ed3f92841ba5bd2",
|
||||
"reference": "4bff79ddd77851fe3cdd11616ed3f92841ba5bd2",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -2719,7 +2719,7 @@
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/composer/pcre/issues",
|
||||
"source": "https://github.com/composer/pcre/tree/3.0.2"
|
||||
"source": "https://github.com/composer/pcre/tree/3.1.0"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -2735,7 +2735,7 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2022-11-03T20:24:16+00:00"
|
||||
"time": "2022-11-17T09:50:14+00:00"
|
||||
},
|
||||
{
|
||||
"name": "composer/semver",
|
||||
@@ -3024,16 +3024,16 @@
|
||||
},
|
||||
{
|
||||
"name": "netresearch/jsonmapper",
|
||||
"version": "v4.0.0",
|
||||
"version": "v4.1.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/cweiske/jsonmapper.git",
|
||||
"reference": "8bbc021a8edb2e4a7ea2f8ad4fa9ec9dce2fcb8d"
|
||||
"reference": "cfa81ea1d35294d64adb9c68aa4cb9e92400e53f"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/cweiske/jsonmapper/zipball/8bbc021a8edb2e4a7ea2f8ad4fa9ec9dce2fcb8d",
|
||||
"reference": "8bbc021a8edb2e4a7ea2f8ad4fa9ec9dce2fcb8d",
|
||||
"url": "https://api.github.com/repos/cweiske/jsonmapper/zipball/cfa81ea1d35294d64adb9c68aa4cb9e92400e53f",
|
||||
"reference": "cfa81ea1d35294d64adb9c68aa4cb9e92400e53f",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -3069,22 +3069,22 @@
|
||||
"support": {
|
||||
"email": "cweiske@cweiske.de",
|
||||
"issues": "https://github.com/cweiske/jsonmapper/issues",
|
||||
"source": "https://github.com/cweiske/jsonmapper/tree/v4.0.0"
|
||||
"source": "https://github.com/cweiske/jsonmapper/tree/v4.1.0"
|
||||
},
|
||||
"time": "2020-12-01T19:48:11+00:00"
|
||||
"time": "2022-12-08T20:46:14+00:00"
|
||||
},
|
||||
{
|
||||
"name": "nikic/php-parser",
|
||||
"version": "v4.15.1",
|
||||
"version": "v4.15.3",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/nikic/PHP-Parser.git",
|
||||
"reference": "0ef6c55a3f47f89d7a374e6f835197a0b5fcf900"
|
||||
"reference": "570e980a201d8ed0236b0a62ddf2c9cbb2034039"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/0ef6c55a3f47f89d7a374e6f835197a0b5fcf900",
|
||||
"reference": "0ef6c55a3f47f89d7a374e6f835197a0b5fcf900",
|
||||
"url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/570e980a201d8ed0236b0a62ddf2c9cbb2034039",
|
||||
"reference": "570e980a201d8ed0236b0a62ddf2c9cbb2034039",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -3125,9 +3125,9 @@
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/nikic/PHP-Parser/issues",
|
||||
"source": "https://github.com/nikic/PHP-Parser/tree/v4.15.1"
|
||||
"source": "https://github.com/nikic/PHP-Parser/tree/v4.15.3"
|
||||
},
|
||||
"time": "2022-09-04T07:30:47+00:00"
|
||||
"time": "2023-01-16T22:05:37+00:00"
|
||||
},
|
||||
{
|
||||
"name": "openlss/lib-array2xml",
|
||||
@@ -3415,16 +3415,16 @@
|
||||
},
|
||||
{
|
||||
"name": "symfony/console",
|
||||
"version": "v5.4.15",
|
||||
"version": "v5.4.21",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/console.git",
|
||||
"reference": "ea59bb0edfaf9f28d18d8791410ee0355f317669"
|
||||
"reference": "c77433ddc6cdc689caf48065d9ea22ca0853fbd9"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/console/zipball/ea59bb0edfaf9f28d18d8791410ee0355f317669",
|
||||
"reference": "ea59bb0edfaf9f28d18d8791410ee0355f317669",
|
||||
"url": "https://api.github.com/repos/symfony/console/zipball/c77433ddc6cdc689caf48065d9ea22ca0853fbd9",
|
||||
"reference": "c77433ddc6cdc689caf48065d9ea22ca0853fbd9",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -3494,7 +3494,7 @@
|
||||
"terminal"
|
||||
],
|
||||
"support": {
|
||||
"source": "https://github.com/symfony/console/tree/v5.4.15"
|
||||
"source": "https://github.com/symfony/console/tree/v5.4.21"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -3510,20 +3510,20 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2022-10-26T21:41:52+00:00"
|
||||
"time": "2023-02-25T16:59:41+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/polyfill-intl-grapheme",
|
||||
"version": "v1.26.0",
|
||||
"version": "v1.27.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/polyfill-intl-grapheme.git",
|
||||
"reference": "433d05519ce6990bf3530fba6957499d327395c2"
|
||||
"reference": "511a08c03c1960e08a883f4cffcacd219b758354"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/433d05519ce6990bf3530fba6957499d327395c2",
|
||||
"reference": "433d05519ce6990bf3530fba6957499d327395c2",
|
||||
"url": "https://api.github.com/repos/symfony/polyfill-intl-grapheme/zipball/511a08c03c1960e08a883f4cffcacd219b758354",
|
||||
"reference": "511a08c03c1960e08a883f4cffcacd219b758354",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -3535,7 +3535,7 @@
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-main": "1.26-dev"
|
||||
"dev-main": "1.27-dev"
|
||||
},
|
||||
"thanks": {
|
||||
"name": "symfony/polyfill",
|
||||
@@ -3575,7 +3575,7 @@
|
||||
"shim"
|
||||
],
|
||||
"support": {
|
||||
"source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.26.0"
|
||||
"source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.27.0"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -3591,20 +3591,20 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2022-05-24T11:49:31+00:00"
|
||||
"time": "2022-11-03T14:55:06+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/polyfill-intl-normalizer",
|
||||
"version": "v1.26.0",
|
||||
"version": "v1.27.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/polyfill-intl-normalizer.git",
|
||||
"reference": "219aa369ceff116e673852dce47c3a41794c14bd"
|
||||
"reference": "19bd1e4fcd5b91116f14d8533c57831ed00571b6"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/219aa369ceff116e673852dce47c3a41794c14bd",
|
||||
"reference": "219aa369ceff116e673852dce47c3a41794c14bd",
|
||||
"url": "https://api.github.com/repos/symfony/polyfill-intl-normalizer/zipball/19bd1e4fcd5b91116f14d8533c57831ed00571b6",
|
||||
"reference": "19bd1e4fcd5b91116f14d8533c57831ed00571b6",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -3616,7 +3616,7 @@
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-main": "1.26-dev"
|
||||
"dev-main": "1.27-dev"
|
||||
},
|
||||
"thanks": {
|
||||
"name": "symfony/polyfill",
|
||||
@@ -3659,7 +3659,7 @@
|
||||
"shim"
|
||||
],
|
||||
"support": {
|
||||
"source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.26.0"
|
||||
"source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.27.0"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -3675,20 +3675,20 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2022-05-24T11:49:31+00:00"
|
||||
"time": "2022-11-03T14:55:06+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/string",
|
||||
"version": "v5.4.15",
|
||||
"version": "v5.4.21",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/string.git",
|
||||
"reference": "571334ce9f687e3e6af72db4d3b2a9431e4fd9ed"
|
||||
"reference": "edac10d167b78b1d90f46a80320d632de0bd9f2f"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/string/zipball/571334ce9f687e3e6af72db4d3b2a9431e4fd9ed",
|
||||
"reference": "571334ce9f687e3e6af72db4d3b2a9431e4fd9ed",
|
||||
"url": "https://api.github.com/repos/symfony/string/zipball/edac10d167b78b1d90f46a80320d632de0bd9f2f",
|
||||
"reference": "edac10d167b78b1d90f46a80320d632de0bd9f2f",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -3745,7 +3745,7 @@
|
||||
"utf8"
|
||||
],
|
||||
"support": {
|
||||
"source": "https://github.com/symfony/string/tree/v5.4.15"
|
||||
"source": "https://github.com/symfony/string/tree/v5.4.21"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -3761,7 +3761,7 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2022-10-05T15:16:54+00:00"
|
||||
"time": "2023-02-22T08:00:55+00:00"
|
||||
},
|
||||
{
|
||||
"name": "vimeo/psalm",
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
{
|
||||
private const TABLE = DB_TABLE_PREFIX . 'posts';
|
||||
|
||||
private const TABLE_SECTIONS = 'sections';
|
||||
private const TABLE_SECTIONS = DB_TABLE_PREFIX . 'sections';
|
||||
|
||||
private $id = null;
|
||||
private $sectionId = null;
|
||||
|
||||
@@ -1,16 +1,255 @@
|
||||
<?php
|
||||
use Core\Models\{DB};
|
||||
use Core\Models\{User, DB};
|
||||
|
||||
const USE_ROUTER = false;
|
||||
$_SERVER['DOCUMENT_ROOT'] = '/home/rsgrinko/sites/dev.it-stories.ru';
|
||||
require_once $_SERVER['DOCUMENT_ROOT'] . '/core/bootstrap.php';
|
||||
|
||||
$DB = DB::getInstance();
|
||||
|
||||
use Workerman\Timer;
|
||||
use Workerman\Worker;
|
||||
|
||||
function replaceBBCode($text_post) {
|
||||
$str_search = array(
|
||||
"#\\\n#is",
|
||||
"#\[b\](.+?)\[\/b\]#is",
|
||||
"#\[i\](.+?)\[\/i\]#is",
|
||||
"#\[u\](.+?)\[\/u\]#is",
|
||||
"#\[code\](.+?)\[\/code\]#is",
|
||||
"#\[quote\](.+?)\[\/quote\]#is",
|
||||
"#\[url=(.+?)\](.+?)\[\/url\]#is",
|
||||
"#\[url\](.+?)\[\/url\]#is",
|
||||
"#\[img\](.+?)\[\/img\]#is",
|
||||
"#\[size=(.+?)\](.+?)\[\/size\]#is",
|
||||
"#\[color=(.+?)\](.+?)\[\/color\]#is",
|
||||
"#\[list\](.+?)\[\/list\]#is",
|
||||
"#\[listn](.+?)\[\/listn\]#is",
|
||||
"#\[\*\](.+?)\[\/\*\]#"
|
||||
);
|
||||
$str_replace = array(
|
||||
"<br />",
|
||||
"<b>\\1</b>",
|
||||
"<i>\\1</i>",
|
||||
"<span style='text-decoration:underline'>\\1</span>",
|
||||
"<code class='code'>\\1</code>",
|
||||
"<table width = '95%'><tr><td>Цитата</td></tr><tr><td class='quote'>\\1</td></tr></table>",
|
||||
"<a href='\\1'>\\2</a>",
|
||||
"<a href='\\1'>\\1</a>",
|
||||
"<img width='150px' src='\\1' alt = 'Изображение' />",
|
||||
"<span style='font-size:\\1%'>\\2</span>",
|
||||
"<span style='color:\\1'>\\2</span>",
|
||||
"<ul>\\1</ul>",
|
||||
"<ol>\\1</ol>",
|
||||
"<li>\\1</li>"
|
||||
);
|
||||
return preg_replace($str_search, $str_replace, $text_post);
|
||||
}
|
||||
|
||||
|
||||
|
||||
$connections = []; // сюда будем складывать все подключения
|
||||
|
||||
// Стартуем WebSocket-сервер на порту 27800
|
||||
$worker = new Worker('websocket://0.0.0.0:8282');
|
||||
$worker->onMessage = function($connection, $data)
|
||||
|
||||
$worker->onWorkerStart = function($worker) use (&$connections)
|
||||
{
|
||||
$connection->send($data);
|
||||
$interval = 5; // пингуем каждые 5 секунд
|
||||
|
||||
|
||||
Timer::add($interval, function() use(&$connections) {
|
||||
foreach ($connections as $c) {
|
||||
// Если ответ от клиента не пришел 3 раза, то удаляем соединение из списка
|
||||
// и оповещаем всех участников об "отвалившемся" пользователе
|
||||
if ($c->pingWithoutResponseCount >= 3) {
|
||||
$messageData = [
|
||||
'action' => 'ConnectionLost',
|
||||
'userId' => $c->id,
|
||||
'userName' => $c->userName,
|
||||
'gender' => $c->gender,
|
||||
'userColor' => $c->userColor
|
||||
];
|
||||
$message = json_encode($messageData);
|
||||
|
||||
unset($connections[$c->id]);
|
||||
$c->destroy(); // уничтожаем соединение
|
||||
|
||||
// рассылаем оповещение
|
||||
foreach ($connections as $c) {
|
||||
$c->send($message);
|
||||
}
|
||||
} else {
|
||||
$c->send('{"action":"Ping"}');
|
||||
$c->pingWithoutResponseCount++; // увеличиваем счетчик пингов
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Timer::add(10, function () use (&$connections) {
|
||||
$infoMessages = [
|
||||
'Случайное число: <b>' . random_int(1000, 9999). '</b>',
|
||||
'Чат разработан командой <a href=\'https://it-stories.ru/\' target=\'_blank\'>it-stories.ru</a> - проекта о веб разработке и программировании',
|
||||
'Это информационное сообщение для проверки работы чата',
|
||||
'Нужен сайт? Студия <a href=\'https://softline71.ru/\' target=\'_blank\'>SoftLine71</a> поможет вам!',
|
||||
];
|
||||
$randomKey = random_int(0, count($infoMessages) - 1);
|
||||
$randMessage = $infoMessages[$randomKey];
|
||||
|
||||
foreach ($connections as $c) {
|
||||
$c->send('{"action":"Information", "text": "' . $randMessage . '"}');
|
||||
$c->pingWithoutResponseCount++; // увеличиваем счетчик пингов
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
$worker->onConnect = function($connection) use(&$connections)
|
||||
{
|
||||
// Эта функция выполняется при подключении пользователя к WebSocket-серверу
|
||||
$connection->onWebSocketConnect = function($connection) use (&$connections)
|
||||
{
|
||||
// Достаём имя пользователя, если оно было указано
|
||||
if (isset($_GET['userName'])) {
|
||||
$originalUserName = preg_replace('/[^a-zA-Zа-яА-ЯёЁ0-9\-\_ ]/u', '', trim($_GET['userName']));
|
||||
}
|
||||
else {
|
||||
$originalUserName = 'Инкогнито';
|
||||
}
|
||||
|
||||
|
||||
// Добавляем соединение в список
|
||||
// + мы можем добавлять произвольные поля в $connection
|
||||
// и затем читать их из любой функции:
|
||||
$connection->userName = $originalUserName;
|
||||
$connection->pingWithoutResponseCount = 0; // счетчик безответных пингов
|
||||
|
||||
$connections[$connection->id] = $connection;
|
||||
|
||||
// Собираем список всех пользователей
|
||||
$users = [];
|
||||
foreach ($connections as $c) {
|
||||
// TcpConnection::id - уникальный идентификатор соединения,
|
||||
// присваивается автоматически. Будем использовать его как
|
||||
// идентификатор пользователя 'userId'.
|
||||
$users[] = [
|
||||
'userId' => $c->id,
|
||||
'userName' => $c->userName,
|
||||
];
|
||||
}
|
||||
|
||||
// Отправляем пользователю данные авторизации
|
||||
$messageData = [
|
||||
'action' => 'Authorized',
|
||||
'userId' => $connection->id,
|
||||
'userName' => $connection->userName,
|
||||
'users' => $users
|
||||
];
|
||||
//$connection->send(json_encode($messageData));
|
||||
foreach ($connections as $c) {
|
||||
$c->send(json_encode($messageData));
|
||||
}
|
||||
|
||||
// Оповещаем всех пользователей о новом участнике в чате
|
||||
$messageData = [
|
||||
'action' => 'Connected',
|
||||
'userId' => $connection->id,
|
||||
'userName' => $connection->userName,
|
||||
'gender' => $connection->gender,
|
||||
'userColor' => $connection->userColor
|
||||
];
|
||||
$message = json_encode($messageData);
|
||||
|
||||
foreach ($connections as $c) {
|
||||
$c->send($message);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
$worker->onClose = function($connection) use(&$connections)
|
||||
{
|
||||
// Эта функция выполняется при закрытии соединения
|
||||
if (!isset($connections[$connection->id])) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Удаляем соединение из списка
|
||||
unset($connections[$connection->id]);
|
||||
|
||||
// Собираем список всех пользователей
|
||||
$users = [];
|
||||
foreach ($connections as $c) {
|
||||
// TcpConnection::id - уникальный идентификатор соединения,
|
||||
// присваивается автоматически. Будем использовать его как
|
||||
// идентификатор пользователя 'userId'.
|
||||
$users[] = [
|
||||
'userId' => $c->id,
|
||||
'userName' => $c->userName,
|
||||
];
|
||||
}
|
||||
|
||||
// Оповещаем всех пользователей о выходе участника из чата
|
||||
$messageData = [
|
||||
'action' => 'Disconnected',
|
||||
'userId' => $connection->id,
|
||||
'userName' => $connection->userName,
|
||||
'users' => $users,
|
||||
];
|
||||
$message = json_encode($messageData);
|
||||
|
||||
foreach ($connections as $c) {
|
||||
$c->send($message);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
$worker->onMessage = function($connection, $message) use (&$connections)
|
||||
{
|
||||
// распаковываем json
|
||||
$messageData = json_decode($message, true);
|
||||
// проверяем наличие ключа 'toUserId', который используется для отправки приватных сообщений
|
||||
$toUserId = isset($messageData['toUserId']) ? (int) $messageData['toUserId'] : 0;
|
||||
$action = isset($messageData['action']) ? $messageData['action'] : '';
|
||||
|
||||
if ($action == 'Pong') {
|
||||
// При получении сообщения "Pong", обнуляем счетчик пингов
|
||||
$connection->pingWithoutResponseCount = 0;
|
||||
} else {
|
||||
// Все остальные сообщения дополняем данными об отправителе
|
||||
$messageData['userId'] = $connection->id;
|
||||
$messageData['userName'] = $connection->userName;
|
||||
|
||||
// Преобразуем специальные символы в HTML-сущности в тексте сообщения
|
||||
$messageData['text'] = htmlspecialchars($messageData['text']);
|
||||
// Заменяем текст заключенный в фигурные скобки на жирный
|
||||
// (позже будет описано зачем и почему)
|
||||
//$messageData['text'] = preg_replace('/\{(.*)\}/u', '<b>\\1</b>', $messageData['text']);
|
||||
$messageData['text'] = replaceBBCode($messageData['text']);
|
||||
|
||||
|
||||
if ($toUserId == 0) {
|
||||
// Отправляем сообщение всем пользователям
|
||||
$messageData['action'] = 'PublicMessage';
|
||||
foreach ($connections as $c) {
|
||||
$c->send(json_encode($messageData));
|
||||
}
|
||||
}
|
||||
else {
|
||||
$messageData['action'] = 'PrivateMessage';
|
||||
if (isset($connections[$toUserId])) {
|
||||
// Отправляем приватное сообщение указанному пользователю
|
||||
$connections[$toUserId]->send(json_encode($messageData));
|
||||
// и отправителю
|
||||
$connections->send(json_encode($messageData));
|
||||
}
|
||||
else {
|
||||
$messageData['text'] = 'Не удалось отправить сообщение выбранному пользователю';
|
||||
$connection->send(json_encode($messageData));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Worker::runAll();
|
||||
Reference in new issue
Block a user