I'm trying to make a notification to my simple php/js chat:
First, I'm trying to compare my log.html (which containing the messages):
my original post.php ( //jQuery request. It posts the client's input and data being sent to the post.php file each time the user submits the form and sends a new message.) The. post.php is saving the messages into log.html file.
<?php
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$text_message = "<div class='msgln'><span class='chat-time'>".date("F j, g:i A")."</span> <b class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars($text))."<br></div>";
file_put_contents("log.html", $text_message, FILE_APPEND | LOCK_EX);
}
?>
my edited post.php (trying to set up a function, which is checking the "new" message - comparing with old ones).
<?php
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$text_message = "<div class='msgln'><span class='chat-time'>".date("F j, g:i A")."</span> <b class='user-name'>".$_SESSION['name']."</b> ".stripslashes(htmlspecialchars($text))."<br></div>";
// Check if content is different
function text_check(){
$ah = fopen("log.html", 'rb');
$aha = preg_match(fread($ah, 8192), $text_message);
$result = true;
while(!feof($ah)) {
if( $aha === false){
$result = false;
break;
}
}
fclose($ah);
return $result;
}
file_put_contents("log.html", $text_message, FILE_APPEND | LOCK_EX);
}
?>
If post.php function "text_check()" return true in my index.php:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
function checkUpdate()
{
$.post("post.php", function(text_check){
if (text_check.toString()=="true") {
playSound();
}
});
}
function playSound()
{
var audio = new Audio('my_audio');
audio.play();
}
Is it a OK conception?
And how can I make an "orang-red blinking" notification, when browser is minimized?
I read something about title - have to change it. Will it work, if I change it every second with JS?
I'm learning WebSocket using PHP library Ratchet. But I have a problem sending the message from client/browser. I have tried using chrome and firefox.
The message is not sent to the server until I disconnect the client by closing the tab or refresh the browser.
Update: My server use Centos 7 with firewalld enabled.
After I close the browser tab, the server output is like this:
Connection 73 sending message "tes" to 1 other connection
Connection 73 has disconnected
Here is the javascript code:
conn = new WebSocket('ws://websocket.develop.local:8080');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log('ada message');
console.log(e.data);
};
conn.onerror = function(e) {
console.log("WebSocket Error: " , e);
//Custom function for handling errors
//handleErrors(e);
};
function sendMessage(){
var message = document.getElementById("pesan").value;
conn.send(message);
console.log('Sending message: ' + message);
};
And here is the PHP code (I got this from Ratchet docs):
<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
Here is the premise of what I'm doing:
I have a program running in the background, a socket server, at all times.
I created a website that calls a php script (using AJAX) that opens a client side socket, connects to the server, sends the request and receives it, then echos it out.
This echo is the response is the 'return value' for my AJAX script.
This is this issue:
When I click a button, the information sends but, sometimes, the information never makes it back to the site.
I know the request is being processed through the server because I can see the request running to completion on the server side.
I know that the information from the server side is sending to the client (the website) because I have a code that checks if data was successfully sent from the server side.
Sometimes the request is sent through and the appropriate response client side (an alert pop-up with information from the server) comes through.
Website Code:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="submit" class="button" name="weather" value="weather" />
<input type="submit" class="button" name="time" value="time" />
<input type="submit" class="button" name="date" value="date" />
</form>
jQuery Code:
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'php/portserverclient.php',
dataSend = {'action': clickBtnValue};
$.post(ajaxurl, dataSend, function (response) {
// Response div goes here.
//$('#servermessage').val($('#servermessage').val()+response);
alert(response);
});
});
PHP Code:
<?php
// -------------------------------------
// ----- Get Information Sent from Site
// -------------------------------------
if (isset($_POST['action']))
{
switch ($_POST['action']) {
case 'weather':
$in = "3";
$request = "Weather";
break;
case 'time':
$in = "2";
$request = "Time";
break;
case 'date':
$in = "1";
$request = "Date";
}
}
else
{
$in = "3";
$request = "Weather";
}
// -------------------------------------
// ----- Open Client Side Socket
// -------------------------------------
error_reporting(E_ALL);
$A1 = "Starting TCP/IP Connection... \n";
/* Get the port for the WWW service. */
$service_port = 51713;
/* Get the IP address for the target host. */
$address = '192.168.8.129';
/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
if ($socket === false)
{
$A2 = "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
exit;
}
else {
$A2 = "Socket Created...OK.\n";
}
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 5, 'usec' => 0));
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 5, 'usec' => 0));
$A3 = "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false)
{
$A4 = "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
exit;
}
else
{
$A4 = "OK.\n";
}
// -------------------------------------
// ----- Send message through socket
// -------------------------------------
$A5 = "Sending $request request...";
$sent = socket_write($socket, $in, strlen($in));
$A6 = "OK.\n";
// -------------------------------------
// ----- Receive response through socket
// -------------------------------------
$out = ' ';
do{$out = socket_read($socket, 20, PHP_NORMAL_READ) ;}
while($out === false);
// -------------------------------------
// ----- Close Client Side Socket
// -------------------------------------
$A7 = "Closing socket...";
$A8 = "OK.\n";
echo "\n From PHP END: ", $A1,$A2,$A3,$A4,$A5,$A6,$A7,$A8,"Message: ", $out,"\n";
socket_shutdown($socket,2);
socket_close($socket);
exit;
?>
C++ Server Side Code:
//---- read buffer ---
sizeofread = read(newsockfd, msg, 20);
if (sizeofread <= 0 || msg[0] == 0x0A || msg[0] == 0x0D || msg[0] == 0x00)
{
// Stops any buggy send (size of read <= 0)
// Stops terminal from sending new line (0x0A & 0x0D) after each press enter
// Stops terminal from sending 0 constantly (0x00)
}
else
{
printf("Received from TCP: %s \n",msg);
//--- Send to Arduino ---
printf( "Sending to Arduino: %s \n", msg);
write( uartt, msg, 20 );
delay(50); // Here to account for how long it takes to send & receive 20 bytes at 9600 Baud
//--- Receive from Arduino ---
while (counter <= 2 && found == false)
{
if ( !( msgLength = serialDataAvail(uartt) ))
{
printf("Nothing to read \n");
delay(1071); // Here to account for how long it takes to receive 1024 bytes at 9600 Baud
counter++;
}
else
{
found = true;
read(uartt, msg, msgLength);
msg[msgLength] = 0;
if (write(newsockfd, msg, 20) < 0)
{
printf("Failed to send to socket \n");
}
else
{
printf("Succesfully sent to socket \n");
}
printf("From the Arduino: ");
printf("%s \n", msg);
}
delay(100);
serialFlush(uartt);
}
counter = 0;
found = false;
close(newsockfd);
goto repeat;
}
Turns out the answer to this riddle was that I needed to disable the Submit buttons default event. Normally, in HTML, the submit button refreshes the page, this must be stopped.
It was stopped like this:
$('.button').click(function(event){
var clickBtnValue = $(this).val();
var ajaxurl = 'php/portserverclient.php',
dataSend = {'action': clickBtnValue};
$.post(ajaxurl, dataSend, function (response) {
alert(response);
});
event.preventDefault();
});
Thanks guys
I've a website that is developed using PHPFox v3.0.7.
Now I'm trying to implement 'SSE(Server Sent Events)' into one of the PHP files. For your reference I'm giving below only the necessary code part of the file. The file is titled as process.class.php and is present at location /var/www/module/notification/include/service/process.class.php present on a server having ip http://34.124.40.142/.
<?php
/**
* [PHPFOX_HEADER]
*/
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
defined('PHPFOX') or exit('NO DICE!');
/**
*
*
* #copyright [PHPFOX_COPYRIGHT]
* #author Raymond Benc
* #package Phpfox_Service
* #version $Id: service.class.php 67 2009-01-20 11:32:45Z Raymond_Benc $
*/
class Notification_Service_Process extends Phpfox_Service
{
/**
* Class constructor
*/
public function __construct()
{
$this->_sTable = Phpfox::getT('notification');
}
public function add($sType, $iItemId, $iOwnerUserId, $iSenderUserId = null)
{
if ($iOwnerUserId == Phpfox::getUserId()&&$iSenderUserId==null)
{
return true;
}
if ($sPlugin = Phpfox_Plugin::get('notification.service_process_add'))
{
eval($sPlugin);
}
if (isset($bDoNotInsert) || defined('SKIP_NOTIFICATION'))
{
return true;
}
$aInsert = array(
'type_id' => $sType,
'item_id' => $iItemId,
'user_id' => $iOwnerUserId,
'owner_user_id' => ($iSenderUserId === null ? Phpfox::getUserId() : $iSenderUserId),
'time_stamp' => PHPFOX_TIME
);
$this->database()->insert($this->_sTable, $aInsert);
echo "data: The notification is generated". PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
return true;
}
}
?>
To access this file ant get event data(i.e. the message "The notification is generated") from it I wrote following simple HTML file having source as process.class.php:
index.html
<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("http://34.124.40.142/module/notification/include/service/process.class.php");
source.onmessage = function(event) {
alert(event.data);
document.getElementById("result").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
But when I run this file in a browser I got following error in a firebug console :
Firefox can't establish a connection to the server at http://34.124.40.142/module/notification/include/service/process.class.php.
Now someone please help me by telling how could I make this file accessible in javascript code written in HTML?
Thanks.
Im kinda new with the sockets stuff and Im trying to make a server on PHP to support websockets calls from my javascript currently my code looks like this
<?php
class Websocket
{
private $server;
private $sockets = [];
public function create($host)
{
$this->server = stream_socket_server('tcp://localhost:8080', $errno, $errmsg);
stream_set_blocking($this->server, 0);
}
public function run()
{
while(true)
{
$client = stream_socket_accept($this->server);
if($client)
{
$data = stream_socket_recvfrom($client, 2048);
if($data)
{
echo 'Client connected'.PHP_EOL;
echo $data;
$response = $this->handshake($data);
stream_socket_sendto($client, $response);
}
}
}
}
private function handshake($data)
{
$data = explode(PHP_EOL, $data);
foreach($data as $header)
{
$current_header = explode(':', $header);
if($current_header[0] == 'Sec-WebSocket-Key')
{
$accept = base64_encode(sha1(trim($current_header[1]).'258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));
$response = 'HTTP/1.1 101 Switching Protocols'.PHP_EOL.'Upgrade: websocket'.PHP_EOL.'Connection: Upgrade'.PHP_EOL.'Sec-WebSocket-Accept:'.$accept.PHP_EOL.PHP_EOL;
return $response;
}
}
}
}
And my javascript is just a simple
var socket = new WebSocket('ws://localhost:8080');
socket.onopen = function(event)
{
console.log('connected');
socket.send('hello');
}
Currently the message connected appears on my chrome console but after that when the hello message is supposed to be sent I get this error
"connection to: xxx was interrupted while the page was loading"
So my question is after I have successfully send the handshake to the client how do I process messages? I know my code is always sending the handshake to new connections but on my server I will only see the first message beeing echoed (the http request) and not the "hello" one
You need to handle the message -
socket.onmessage = function(e){
var server_message = e.data;
console.log(server_message);
}