Websockets : Send message from php server to clients - php

I'm trying to send messages from my file index.php (server) to clients connected using websockets.
My javascript file to create the client connection :
var websocket_server = new WebSocket("ws://localhost:4950/");
websocket_server.onopen = function(e) {
console.log("connected");
}
websocket_server.onmessage = function(e)
{
console.log('message received from server');
}
index.php:
$msg = "Message from server";
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n");
socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR,1) or die("prbl options\n");
socket_connect($sock, '127.0.0.1', 4950) or die("could not connect\n");
socket_write($sock, $msg, strlen($msg));
The client connect to the websocket is successful, but when I run the PHP file, I get nothing (no error and no message in the console).
In other words, javascript doesn't consider my socket_write as a message :/
Any ideas? :)

I have found a solution thanks to #ADyson ;)
I'm using SSE server sent events now and it works !But I'd like to know if my code is 'proper' or if there is a more 'adequate' way.
I'm using session superglobals to pass server informations changes to another file which is constantly reading it as event-stream (that's the way SSE works).
index.php :
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="jquery.js">
</script>
<script type="text/javascript" src="stream.js">
</script>
</head>
<body>
<a>Receive message</a>
</body>
</html>
stream.js (listening to the server) :
var serv = new EventSource("server.php");
serv.onmessage = function(e) {
var jdata = JSON.parse(e.data);
console.log(jdata.message);
};
serv.onopen = function(e) {
console.log('Connection opened');
}
$(document).ready(function(){
$('a').click(function(){
receive_msg();
});
});
function receive_msg(){
$.ajax({
type: "POST",
url: 'controller.php',
data: {action: 'send'}
});
}
controller.php :
<?php
session_start();
if (isset($_POST['action'])) {
$_SESSION['server']="you have received a message";
}
server.php :
<?php
session_start();
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
if (isset($_SESSION['server'])) {
$data = array(
'message'=> $_SESSION['server']
);
$data = json_encode($data);
echo "data: {$data}\n\n";
unset($_SESSION['server']);
}
The way it works :
Clients connect to the server.php and read the file constantly. When the server wants to send a message to clients, it creates a session variable. Server.php reads the variable and pass it to my js file. Then the variable is destroyed so we pass the message only once.

Related

Keep swoole websocket runing even if terminal is closed

I am trying to create a chat application using Socket and using Swoole as backend. I successfully create a connection to server-client but the issue I am facing now is that whenever I close terminal WebSocket is unable to connect.
Server code:-
<?php
//Create the websocket server object
$websocket_server = new swoole_websocket_server("MY_IP", 3000);
// Register function of the opening connection event
$websocket_server->on('open', function($websocket_server, $request){
var_dump($request->fd, $request->get, $request->server);
$websocket_server->push($request->fd, "Hello welcome\n");
});
// Register function of the receiving message event
$websocket_server->on('message', function($websocket_server, $frame){
echo "Message : {$frame->data}\n";
$websocket_server->push($frame->fd, "Server : {$frame->data}");
});
// Register function of the close event
$websocket_server->on('close', function($websocket_server, $fd){
echo "client_{$fd} is closed\n";
});
// Start the server
$websocket_server->start();
Client side Code:-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script type="text/javascript">
var wsServer = 'ws://IP:3000';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {
console.log("Connected to WebSocket server.");
};
websocket.onclose = function (evt) {
console.log("Disconnected");
};
websocket.onmessage = function (evt) {
console.log('Retrieved data from server: ' + evt.data);
};
websocket.onerror = function (evt, e) {
console.log('Error occured: ' + evt.data);
};
</script>
</body>
</html>
Everything is working fine the only issue is when we close terminal web socket id down.
I get the answer on Git. Please add below code in line
$websocket_server = new swoole_websocket_server("MY_IP", 3000);
$websocket_server->set([
'daemonize' => true,
]);

auto refresh the div with dynamic data

I have a div section. I want to reload this section every 5 seconds. How do I do this. Here is my code:
<script>
$("#send_parent_general_chat").submit(function()
{
var rec = $("#data").val();
var msg = $("#msg").val();
var dataString = 'rec='+ rec + '&msg='+ msg;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "Client/send_general_parent_chat_msg/<?php echo $per_job->id;?>",
data: dataString,
cache: false,
success: function(result){
$('#display_general_msg').html(result);
$('#send_parent_general_chat')[0].reset(); //form reset
}
});
return false;
});
</script>
<script>
$(document).ready(function(){
setInterval(function(){
// alert("===111==");
$("#display_general_msg").load('<?php echo base_url(); ?>" + "Client/refresh_general_parent_chat_msg/<?php echo $per_job->id;?>')
}, 5000);
});
</script>
I have created one more controller for refreshing the div I have used the time interval function but it is not loading, it shows this error:
Access forbidden!
You don't have permission to access the requested object. It is either read-protected or not readable by the server.
If you think this is a server error, please contact the webmaster.
Error 403
I need to refresh only the div content not the whole page.
How do I achieve this?
You can Use :
setTimeout(function()
{
Your_Function(); //this will send request again and again;
}, 5000);
Replace Your_Function with your Function Name.
Hope this will help !!
Below is an example which will update the contents in every 5 seconds using php websockets. This is a simple example, but you can use it to modify to fit for your application needs. You don't need the timeout functions on the client side here we use server sleep
Install the Workerman socket library
composer require workerman/workerman
The client side code
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
//alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:2346");
ws.onopen = function() {
// Web Socket is connected, send data using send()
ws.send("Message to send");
//alert("Message is sent...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
//alert("Message is received..." + received_msg);
document.getElementById("demo").innerHTML = "Timestamp is updated every 5 sec " +received_msg;
};
ws.onclose = function() {
// websocket is closed.
alert("Connection is closed...");
};
} else {
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id = "sse">
Run WebSocket
</div>
<div id="demo" style="font-size: 64px; color: red;"></div>
</body>
</html>
The Server side code
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Workerman\Worker;
// Create a Websocket server
$ws_worker = new Worker("websocket://0.0.0.0:2346");
// 4 processes
$ws_worker->count = 4;
// Emitted when new connection come
$ws_worker->onConnect = function($connection)
{
echo "New connection\n";
};
// Emitted when data received
$ws_worker->onMessage = function($connection, $data)
{
// Send hello $data
while(true) {
$connection->send(time());
sleep(5); //Sleep for 5 seconds to send another message.
}
};
// Emitted when connection closed
$ws_worker->onClose = function($connection)
{
echo "Connection closed\n";
};
// Run worker
Worker::runAll();
The backend service can be started with the following command from the terminal or you can autostart on boot if you want.
$php index.php start
Here index.php is our backendnd file name.
Just start the service and load the page then you can see the timestamp is updated every 5 seconds which comes from the server side. This is a working example tested on my local machine. Try and let me know if you need any other help.
The output
you can also try below one:
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 5000);
setInterval approach will be more accurate than the setTimeout approach
// or
$(function(){ // document.ready function...
setTimeout(function(){
$('form').submit();
},5000);
});

Trying to use php site with socket.io chat application but it downloads php code instead

I have created a chat application using the walk through on socket.io
I have added further content to the application, including database info, which meant I had to change the index.html to current session.php.
Now when I try and run the application, it just downloads a document with all the code for the page, and it does not run.
I have changed all the code to current session.php where necessary.
If I change the file name back to current session.html and change the relevant code, it then works fine....
I really need to have database info on the page, which is why it needs to be current session.php
Does anyone know why it does this? Is there a work around?
Code for index.js:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/currentsession', function(req, res){
res.sendFile(__dirname + '/Staff/html/current session.php');
});
app.get('/question', function(req, res){
res.sendFile(__dirname + '/Student/Question.php');
});
io.emit('some event', { for: 'everyone' });
io.on('connection', function(socket){
socket.broadcast.emit('hi');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
var nsp = io.of('/currentsession');
nsp.on('connection', function(socket){
socket.join('/currentsession');
});
var nsp = io.of('/question');
nsp.on('connection', function(socket){
socket.join('/question');
});
var nsp = io.of('/currentsession');
nsp.on('connection', function(socket){
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
var nsp = io.of('/currentsession');
nsp.on('connection', function(socket){
socket.on('go-to-page', function(data){
io.of('/question').emit('go-to-page', { href: "//selene.hud.ac.uk/u1555602"});
});
});
http.listen(4000, function(){
console.log('listening on *:4000');
});
code for current session.php
<?php include('server.php') ?>
<?php
if (!isset($_SESSION['username'])) {
$_SESSION['msg'] = "You must log in first";
header('location: sign in.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Wireless Response System</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="../css/style.css" rel="stylesheet" type="text/css">
</head>
<div class="heading">
<div class="php">
<?php
if (isset($_SESSION['username'])) :
$query = ("SELECT discipline FROM user WHERE username = '".$_SESSION['username']."'");
$resultset = $conn->query($query);
while ($user = $resultset->fetch()) {
echo '<h1> Discipline:'; echo $user["discipline"]; '</h1>'; }
endif
?>
</div>
<nav>
<ul>
<form action="">
<button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io('/currentsession');
$('form').submit(function(){
socket.emit('go-to-page', $('#m').val());
$('#m').val('');
return false;
});
socket.on('go-to-page', function (data) {
window.location.replace(data.href);
});
});
</script>
res.sendFile(__dirname + '/Staff/html/current session.php');
You have written an HTTP server using Node.js.
For some HTTP requests, your server will respond by reading the source code of a PHP file and then sending it to the browser.
You need to run the PHP program and send its output, not the source code.
Typically you would do this by using a server optimised for running PHP (such as Apache HTTPD) and having the browser make the request to that server and not the one created using Node.js.

Comunication between Express.js and PHP through jQuery Ajax

I'm developing a small project where I have a web page (index.html) loading in Express.js and it sends some data to a PHP script running on a MAMP server. The PHP script processes the data and returns a JSON encoded array back to the web page and finally the Node.js server sends data to connected clients using socket.io.
I have problems with the communication with PHP using jQuery Ajax. I send the data to PHP using POST and I know PHP receives that data but I don't know how to catch the response from PHP to know how the processing went.
I have no experience with Node.js. What can I do to make this thing work?
So far this is the code I have
Node.js - Express.js
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, db = require('./routes/db')
, http = require('http')
, socketio = require('socket.io')
, path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser()); //Middleware
app.use('/', express.static(__dirname + '/public'));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app);
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
HTML Page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Site</title>
<script src="js/jquery-2.0.3.min.js" type="text/javascript"></script>
</head>
<body>
<div id="formContainer">
<form enctype="multipart/form-data">
<input type="text" name="texto">
<button type="button" id="buttonSend">Enviar</button>
</form><br/><br/>
</div>
<script type="text/javascript">
$('#buttonSend').click(function(e){
e.preventDefault();
$.ajax({
url: 'http://localhost:8080/NodePHP/test.php',
type: 'POST',
dataType: "json",
data: {value: 1},
success: function(data){
if(data.success == true){
alert("Perfect!");
}
else{
alert("Error!");
}
},
error: function(xhr,status,error){
//alert("Error de llamada al servidor");
alert(xhr.responseText);
//$('#botonUsarFoto').css('display','block');
}
});
});
</script>
</body>
</html>
PHP Script
<?php
$number = $_POST['value'];
echo $number;
// move the image into the specified directory //
if ($number == 1) {
$data = array("success"=>"true");
echo json_encode($data);
} else {
$data = array("success"=>"false");
echo json_encode($data);
}
?>
Thanks in advance for any help
In order to make a request with Node, we'll use the http and querystring modules. Here's an example lovingly adopted from the Nodejitsu folks:
var http = require('http');
var querystring = require('querystring');
var data = querystring.stringify({
value: 1
});
var options = {
host: 'localhost',
path: '/myPHPScript',
method: 'POST'
};
callback = function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
var req = http.request(options, callback);
req.write(data);
req.end();
Alternatively, you could use the request module, but first things first.

Getting information from Pusher channel using PHP

I'm getting new to "Pusher" (the websocket api) and I'm having hard time to understand how can I fetch information from the server after sending it to the channel.
For example, this is my code:
<?php
include "pusher/Pusher.php";
?>
<script src="http://js.pusher.com/2.1/pusher.min.js"></script>
<script type="text/javascript">
var pusher = new Pusher('c77c12b92e38f4156e9c');
var channel = pusher.subscribe('test-channel');
channel.bind('my-event', function(data) {
alert('An event was triggered with message: ' + data.message);
});
</script>
<?php
$pusher = new Pusher($config["pusher_key"], $config["pusher_secret"], $config["pusher_id"]);
$pusher->trigger(channel, 'my-event', array('message' => 'Test Message') );
Now, my information is sent to the server, but I don't know how to get it.
Thanks.
You can find the source for a very simple example here:
https://github.com/leggetter/pusher-examples/tree/master/php/hello-world/src
And this example working here:
http://www.leggetter.co.uk/pusher/pusher-examples/php/hello-world/src/
The problem you are seeing is that you are triggering the event on the server before the page has rendered in the browser. So, a connection has not been made by the browser to Pusher, nor has a subscription been made.
You can try something liked this,for php pusher library I used composer
<div class="notification">
</div>
<script>
var pusher = new Pusher('APP_KEY');
var notificationsChannel = pusher.subscribe('notification');
notificationsChannel.bind('new_notification', function(notification){
var message = notification.message;
toastr.success(message);
});
var sendNotification = function(){
var text = $('input.create-notification').val();
$.post('./notification/index.php', {message: text}).success(function(){
console.log('Notification sent!');
});
};
$('button.submit-notification').on('click', sendNotification);
</script>
HTML
<input class="create-notification" placeholder="Send a notification :)"/>
<button class="submit-notification">Go!</button>
Using PHP in this case
require(dirname(__FILE__).'/../vendor/autoload.php');
$app_id = 'APP_ID';
$app_key = 'APP_KEY';
$app_secret = 'APP_SECRET';
$pusher = new Pusher($app_key, $app_secret, $app_id,array( 'encrypted' => true ));
$data['message'] = $_POST['message'];
$pusher->trigger('notification', 'new_notification', $data);
For more follow this link
Recommended folder structure -
You can add following for more UX kind'a look -
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css">
<script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<script src="http://js.pusher.com/2.2/pusher.min.js" type="text/javascript"></script>

Categories