I would like to make a web interface in PHP to see the FreeSWITCH activities (calls, etc), possibly hosted on a different server than the one where FS is running.
I've seen the server status on the FS server using command line (php single_command.php status), but now I would like to see this status from another server.
When I try to copy ESL.php file to this remote server and try to check the status, I get this error message:
Fatal error: Call to undefined function new_ESLconnection() in
/var/www/freeswitch/ESL.php on line 127
This is my index.php file:
<?php
ini_set('display_errors', 1);
$password = "ClueCon";
$port = "8021";
$host = "192.168.2.12";
require_once('ESL.php');
set_time_limit(0); // Remove the PHP time limit of 30 seconds for completion due to loop watching events
// Connect to FreeSWITCH
$sock = new ESLconnection($host, $port, $password);
// We want all Events (probably will want to change this depending on your needs)
$sock->sendRecv("status");
// Grab Events until process is killed
while($sock->connected()){
$event = $sock->recvEvent();
print_r($event->serialize());
}
?>
I undestand that the webserver doesn't have FreeSWITCH installed, so the error message is obvious, but i don't see how to access to this information from this webserver.
Thank you for your help.
Depending upon your need you can use either Inbound or Outbound socket. I do not know much about PHP and FS Event Socket but yeah tried enough with python. I highly recommended to go through thislink.
So if you just want to do small task like initiating a call, bridging any two given number etc i think you should go with Inbound socket(making cli command from your web server to freeswitch server) or mod_xml_rpc.
And if you want to have full control of everything that happens on FS server like showing live call status and modifying their states or say a complete interactive telephony dashboard then you should go with Outbound socket.(Your FS server will send all events to your web server.)
However in your case problem is I think you did not properly build the php ESL module.
this link might help you installing ESL
Rather than using ESL, you might want to consider using the XMLRPC. The connection is very straight forward:
https://wiki.freeswitch.org/wiki/Freeswitch_XML-RPC
The credentials for the XMLRPC are in your autoloads_configs/xml_rpc.conf.xml
Related
I'm building a dashboard that allows me to visualise my crontab as it runs (Think a queue of upcoming tasks, those that are running currently and those that have finished and whether the outcome was successful.) To do this, I need to send messages from the tasks (running or monitored by PHP) on my server, to the client browsers that run the dashboard using javascript. It also has to be secure.
To solve this issue I implemented a Twisted/Autobahn socket server in Python, which worked fine once I had paid for proper security certificates. The problem I have however is getting the PHP running the crontasks to be able to send messages to the webSocket server which passes them on to the client browsers, so far I have hacked this by writing a Python client that accepts the message to send as an argument and run this as an exec from PHP.
Obviously this is not a robust solution (which is also relatively slow to execute) and I'd now like to send logfile entries from the crontasks over websockets to my dashboards so I can see what's happening on my servers as tasks run. I've been looking for a while and tried various approaches (most are too long to post) however they range from tutorials, to segments from the PHP website to libraries such as Thruway (which seems too over-engineered for my use case, specialised and hard to adapt).
The best progress I have so far is Pawl, and using the following code I'm able to successfully send three messages to the Python Socket Server using wss:
<?php
require __DIR__ . '/vendor/autoload.php';
\Ratchet\Client\connect('wss://127.0.0.1:9000')->then(function($conn) {
$conn->on('message', function($msg) use ($conn) {
echo "Received: {$msg}\n";
$conn->close();
});
$conn->send('MSG 1');
$conn->send('MSG 2');
$conn->send('MSG 3');
}, function ($e) {
echo "Could not connect: {$e->getMessage()}\n";
});
?>
(Note that this depends on the libraries found here)
The problem I have is that I would like to be able to open and close the connection and send messages as separate steps, in the code example (which I've had difficulty adapting) it seems that as open, send and close are all wrapped in the then method and anonymous function I cannot call these methods seperately. Ideally I'd like to open the connection at the beginning of my crontask execution, each time a message is logged call the send method and close the connection at the end without wasting time opening and closing a connection to my socket server for each and every message. Please note that listening for replies isn't necessary.
Also, any solutions that work to 127.0.0.1:9000 over WSS and don't need libraries or use a different one I'm happy to consider. Please also note (after seeing other posts) this question specifically refers to a websocket client, not a server.
Many thanks,
James
Leaving this in case anybody else finds this final solution welcome:
In the end I wrapped a module called Textalk by Fredrik Liljegren et al in a small class to make it more accesible and this solved my issue.
Here is the code I used in the end:
require('vendor/autoload.php');
use WebSocket\Client;
class secureSocketClient {
private $OClient;
function __construct($VProtocol, $VLocation, $VPort, $VDir) {
$this->OClient = new Client("$VProtocol://$VLocation:$VPort" . ($VDir != null ? "/$VDir" : ""));
}
function sendMessage($ORequestData) {
$VLocalMessage = json_encode($ORequestData);
$this->OClient->send($VLocalMessage);
}
function __destruct() {
$this->OClient->close();
}
}
Which can be invoked as so:
require_once <class location>
$this->OSecureSocketClient = new secureSocketClient("wss", "127.0.0.1", "9000", null);
$this->OSecureSocketClient->sendMessage($OMSG1);
$this->OSecureSocketClient->sendMessage($OMSG2);
$this->OSecureSocketClient->sendMessage($OMSG3);
To install textTalk (on linux), you can use the following commands in the directory where the class will reside:
curl -sS https://getcomposer.org/installer | php
add the following to composer.json (in the same directory):
{
"require": {
"textalk/websocket": "1.0.*"
}
}
then run the following:
sudo php composer.phar install
Regards,
James
I've inherited an issue on a Joomla site running on PHP 5.5 on IIS 7.5. Currently it accesses a SQL server through our firewall as part of a query, but this server may not always be available so I wanted to make sure the script dealt with this gracefully. We connect with
$itemodbc = "Driver={SQL Server Native Client 10.0};Server=$itemserver;Database=$itemdatabase;";
$con = odbc_connect($itemodbc,$itemuser,$itempassword) or die('SQL connection error');
but if I simulate the server being unavailable by changing the server's IP address this takes ages and eventually the page script (I believe) times out and errors. What I want to do is set this timeout to 5 or 10 seconds, and if this times out then I can continue the script only using the server's local database content, but I can't find where to set this up. I've found the mssql.connect_timeout entry in the php.ini but this doesn't make any difference (I'm sure this is for mssql_connect calls, rather than odbc_connect, so this makes sense), and there doesn't seem to be an ODBC equivalent, I've also tried appending "Timeout=10;" to the ODBC connection string, but this also doesn't seem to work. Hunting round google I have found what seem to be the settings for a Linux system, but obvisously that also isn't helpful. Where do I need to set this in Windows, or do I need to convert it to another database connection type?
I imagine you have this solved already, but I would have used some kind of PHP based code to 'test' if the server was online. A quick google showed this might be a possible solution for your problem (just change google.com to the direct route to your server, maybe an IP on a different port, or maybe something like server.companyhost.com)
function availableUrl($host, $port=80, $timeout=10) {
$fp = fSockOpen($host, $port, $errno, $errstr, $timeout);
return $fp!=false;
}
//Return "true" if the url is available, false if not.
if (!availableUrl("www.google.com")) {
print " some message that the server is down with neat html that suits your needs ";
exit;
}else{
//the connection is ok... proceed
}
I want to write my own, small website for controlling my own GPS localizers. The problem is, that they are sending data (over GPRS) using UDP, not HTTP protocol. Can anyone give me any advice on how to receive such data and put it into MySQL database?
I'm looking for something exactly as written in this answer to that question. The only problem is that site mentioned in this answer has expired and script is unavailable.
All I need is an advice or example on how can I receive UDP packet/datagram containing coordinates, speed, date etc. and put this data into MySQL database. How to write a gateway as easiest as possible? All the rest I can handle myself.
I could do this without problems on Windows, as I'm former Delphi developer and writing a gateway between UDP and MySQL isn't a hard job to do there. But I need to run this solution (gateway) on a small, week Linux-based server, which isn't able to run Kylix (Delphi for Linux) programs, so this way is a dead-end.
Can this be done using PHP, JavaScript or by writing Bash script? I was thinking about node.js, which has similar example on home webpage (and probably many more out in the Internet). But I'm not to familiar with node.js, therefore I don't know, if there aren't better/easiers ways to do this.
It's possible to read data from UDP port using PHP. I am posting a example code which reads data from udp port.
<?php
error_reporting(E_ALL | E_STRICT);
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($socket, '127.0.0.1', 1223);
$from = '';
$port = 0;
socket_recvfrom($socket, $buf, 12, 0, $from, $port);
echo "Received $buf from remote address $from and remote port $port" . PHP_EOL;
?>
and to insert that data into MySQL database may be you need to use a daemon, go through this link
http://phpdaemon.net/
Maybe socket_recvfrom might interest you?
Here is, what I found myself.
General
As Venkat wrote, you can write a simple listner in pure PHP. You only have to run it via SSH, in PHP in CLI SAPI mode, not via browser, as it will fail on timeout after about 3-5 minutes.
For running in CLI mode, you need to know a full path to PHP and you have to call it with proper switch. For example:
/mnt/ext/opt/apache/bin/php -f /share/Web/projects/gps/gateway.php
PHP CLI does not use stdout for echo (don't know, what it uses). So, replace any echo with storing values to file or database, to see actual effects of your listner working.
You may need to use set_time_limit(0) function for endless, uninterrupted execution; but it was reported (see user contributed notes here), it is hardcoded to 0 for CLI SAPI, so setting this may not be mandatory.
After running your script in CLI mode, you can break it, by using Ctrl+C.
Listner example
Here is an example of a listner, that drops everything, it receives into 'drop.txt' file in the same directory, where script file is placed:
error_reporting(E_ALL | E_STRICT);
$file = './dump.txt';
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($socket, '0.0.0.0', 12345);
while(TRUE)
{
$buf = '';
$from = '';
$port = 0;
socket_recvfrom($socket, $buf, 1024, 0, $from, $port);
$momentum = time();
$entry = $momentum.' -- received "'.trim($buf).'" from '.$from.' on port '.$port.PHP_EOL;
file_put_contents($file, $entry, FILE_APPEND | LOCK_EX);
}
Things, you should keep in mind:
This script uses infinite loop, so the only way to break it after running is to cast Ctrl+C.
Use 0.0.0.0 IP address in socket_bind to listen from all sources (IP addresses) or 127.0.0.1 to limit it to localhost only.
Carefully select third parameter in socket_recvfrom -- a maximum number of bytes that will be received -- to make sure that the data you're waiting for will not be truncated.
You must use full path to files, you're using -- that is why there is $file = './dump.txt', not $file = 'dump.txt' in the code. Without full path, it can only work via webbrowser.
Using database
If you decide to drop recevied UDP packets into database and you choose SQLite for this purpose, you not only have to provide full path to database file, but also an absolute path! So:
$dbhandle = new SQLiteDatabase('/share/Web/projects/gps/data.db');
not:
$dbhandle = new SQLiteDatabase('data.db');
or even:
$dbhandle = new SQLiteDatabase('./data.db');
Second and third attempt will fail on some systems (depending on PHP configuration) and in this case, you'll see warning, that there is no such table, you're looking for, in database file.
Logoff problem fix
If you don't have direct access to the machine, on which you'll be running that listener, and you're connecting via SSH, keep in mind, that your listener will be problably turned off, once you logoff.
To fix this problem, you have to either run your PHP script in daemon mode (by adding & at the end):
/mnt/ext/opt/apache/bin/php -f /share/Web/gps/gateway.php&
Or make use of screen command in run non-daemon version of your listener in "wirtual" terminal.
I am trying to get my head round node.js...
I am very happy with my LAMP set up as it currently fulfils my requirements. Although I want to add some real-time features into my PHP app. Such as showing all users currently logged into my site and possible chat features.
I don't want to replace my PHP backend, but I do want scalable real-time solutions.
1. Can I throw node.js into the mix to serve my needs without rebuilding the whole application server-side script?
2. How best could node.js serve my 'chat' and 'currently logged in' features?
Great to hear your views!
W.
I suggest you use Socket.io along side node.js. Install and download the libs from http://socket.io/. You can run it along side your Apache server no problems.
First create a node server:
var http = require('http')
, url = require('url')
, fs = require('fs')
, io = require('../')//path to your socket.io lib
, sys = require(process.binding('natives').util ? 'util' : 'sys')
, server;
server = http.createServer(function(req, res){
var path = url.parse(req.url).pathname;
}),
server.listen(8084);//This could be almost any port number
Second, run your server from the command line using:
node /path/to/your/server.js
Third, connect to the socket using client side js:
var socket = new io.Socket(null, {port: 8084, rememberTransport: false});
socket.connect();
You will have to have include the socket.io lib client side aswell.
Send data from client side to the node server using:
socket.send({data:data});
Your server.js should also have functions for processing requests:
io.on('connection', function(client){
//action when client connets
client.on('message', function(message){
//action when client sends msg
});
client.on('disconnect', function(){
//action when client disconnects
});
});
There are two main ways to send data from the server to the client:
client.send({ data: data});//sends it back to the client making the request
and
client.broadcast({ data: data});//sends it too every client connected to the server
I suspect the chat as well as the logged in listing would work via Ajax.
The chat part would be pretty easy to program in Node.js, use one of the mysql modules for Node to connect to your existing database and query login information and such and then do all the actual chatting via Node.js, I recommend you to check out Socket.io since it makes Browser/Node.js communcation really trivial, this should allow you to focus on the actual chat logic.
Also, you could take a look at the "official" chat demo of Node.js, for some inspiration.
As far as the currently online part goes, this is never easy to implement since all you can do is to display something along the lines of "5 users active in the last X minutes".
Of course you could easily add some Ajax that queries the chat server and display the userlist from that on the homepage.
Or you completely crazy and establish a Socket.io connection for every visitor and monitor it this way, although it's questionable whether this is worth the effort.
What about using a socket file
just like pedro did with ngnx ?
http://nodetuts.com/tutorials/25-nginx-and-nodejs.html
You can run php from node js using node-php: https://github.com/mkschreder/siteboot_php
I'm running a wss (secure websocket) server alongside my LAMP setup.
Node.js can easily run alongside any other web server (apache) you want. In #KitCarrau example, he lets node run on port 8084 - that's where it's running and listening to, not 80 or 443 etc (those are usually taken by apache anyway). But you can still use the same port to also serve http/https (in my case just stating some conf and general info that the service is up).
Starting from the console isn't the best way (remotely, node stops when closing the console).
I recommend taking a look at Running node as service
Easy to track log in realtime (log with console.log("hello"); in your application) with:
tail -f /var/.../SocketServer.log
Sample script (node-server.conf):
author ....
description "node.js server"
# used to be: start on startup
# until we found some mounts weren't ready yet while booting:
start on started mountall
stop on shutdown
# Automatically Respawn:
respawn
respawn limit 99 5
# Max open files are # 1024 by default. Bit few.
limit nofile 32768 32768
script
# Not sure why $HOME is needed, but we found that it is:
export HOME="/root"
exec node /var/.../SocketServer.js >> /var/www/node/.../SocketServer.log 2>&1
end script
post-start script
# Optionally put a script here that will notifiy you node has (re)started
# /root/bin/hoptoad.sh "node.js has started!"
echo "\n*********\nServer started\n$(date)\n*********" >> /var/.../SocketServer.log
end script
I'm making a GWT project that uses PHP to connect to a DB2 database. When I compile the project and deploy it to the server (copy the contents of the WAR directory over), it works fine, obviously in hosted mode I run into the SOP issue since GWT is on port 8888 while the php script is running on port 80.
I'm trying to get the -noserver option to work but I must be missing something.. I went back and created the basic sample app from the command line (webApplicationCreator -out /home/mike/gwt/sample1)
I edited the build.xml to include the -noserver and -port 80 arguements for devmode. I want my app to be hosted at localhost/sample1 so I edited the -startupUrl to the whole URL I want to use: http://localhost/sample1/sample1.html
I compiled (ant), copied over the sample1.html, sample1.css from war to the webserver sample1 directory, and the (md5).gwt.rpc, clear.cache.gif, sample1.nocache.js and hosted.html files from the war/sample1 to sample1/sample1 directory as described in the GWT documentation (no history.html file was created).
I then run ant devmode from the project directory (/home/mike/gwt/sample1)
I can get to the sample1.html page, but when I click the button to send the name to the server it returns with
Remote Procedure Call - Failure
Server replies:
An error occurred while attempting to contact the server. Please check your network connection and try again.
I turned on firebug and it's returning a 404 for http://localhost/sample1/sample1/greet. This is where I'm stuck.. this file obviously doesn't exist on my webserver.. but why? Isn't this something that is supposed to be getting compiled by GWT?
Can anyone give me a hand? Thanks!
So, basically you've copied over the client-side of a client/server application. When your GWT client application attempts to make a Remote Procedure Call (RPC) to the server to a greeting service that is part of the initial sample, it can't find that service.
If you wanted to copy that service over, you'd need to have a Java application server, copy over the GreetingService, the web.xml that references it and possibly a few other things (I'd have to check in more detail). That doesn't sound like what you actually want, so either you'll want to build a GWT-RPC service in PHP that responds to that URL, or remove the reference in the GWT code to RPC call to the greeting service.
With a PHP back-end, you're probably not going to use GWT-RPC, I'm guessing that you're more likely to use JSON or XML, and if that's the case, then I'd go with removing the RPC call altogether for now.
Does this all make sense? Feel free to ask for further clarification.
To solve the SOP issue, I used the HttpProxyServlet to proxy the HTTP requests to my webserver through the development server.
Download httpProxyPackage.jar, copy it into WEB-INF/lib/, and configure it like so in WEB-INF/web.xml (this is for the StockWatcher tutorial, assuming your web root is the folder that contains the StockWatcher directory):
<servlet>
<servlet-name>jsonStockData</servlet-name>
<servlet-class>com.jsos.httpproxy.HttpProxyServlet</servlet-class>
<init-param>
<param-name>host</param-name>
<param-value>http://localhost/StockWatcher/war/stockPrices.php</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>jsonStockData</servlet-name>
<!--
http://127.0.0.1:8888/stockPrices.php in dev mode
http://gwt/StockWatcher/war/stockPrices.php in prod mode
-->
<url-pattern>/stockPrices.php</url-pattern>
</servlet-mapping>
Then redefine your JSON URL as:
GWT.getHostPageBaseURL() + "stockPrices.php?q=";
instead of:
GWT.getModuleBaseURL() + "stockPrices.php?q=";
It’s maybe not the best way, but if it can get someone else started… There was another way using php-cgi, but I didn’t have it installed.