Socketing C++ to PHP or Android - php

I have code for client - server. Server code use C++ with local port and the client i wanna make use PHP or Android. But I dont't know how to make the code.
NB :
Server App use local port 10001
My code server like this (networkex.cpp)
bool CNetworkEX::LoginStatRequest(int n, char* pMsg)
{
_login_server_stat_request_aclo* pRecv = (_login_server_stat_request_aclo*)pMsg;
_login_server_stat_result_loac Send;
Send.wClientIndex = pRecv->wClientIndex;
if ( pRecv->byStat == 0 )
{
}
else if ( pRecv->byStat == 1 )
{
g_Main.m_bExternalOpen = true;
::StringOutput("Connection External Open");
}
else if ( pRecv->byStat == 2 )
{
g_Main.m_bExternalOpen = false;
::StringOutput("Connection External Close");
}
if ( g_Main.m_bExternalOpen )
Send.byRet = 1;
else
Send.byRet = 2;
BYTE byType[msg_header_num] = {system_msg, login_server_stat_result_loac};
m_pProcess[LINE_ACCOUNT]->LoadSendMsg(0, byType, (char*)&Send, Send.size());
return true;
}
My main (mainthread.cpp)
bool CMainThread::CommandProcess(char* pszCmd)
{
int nWordNum = ::ParsingCommand(pszCmd, max_cheat_word, s_pszDstCheat, max_cheat_word_size);
if(nWordNum <= 0)
return false;
if(!strcmp("/open", s_pszDstCheat[0]))
{
::StringOutput("Connection External Open");
m_bExternalOpen = true;
return true;
}
else if(!strcmp("/close", s_pszDstCheat[0]))
{
::StringOutput("Connection External Close");
m_bExternalOpen = false;
return true;
}
else if(!strcmp("/patchup", s_pszDstCheat[0]))
{
DWORD dwBufNum = m_dwPatchServerNum + 1;
if(dwBufNum > MAX_PATCHER_PER_GLOBAL)
dwBufNum = MAX_PATCHER_PER_GLOBAL;
::StringOutput("Patch Server increases(%d -> %d)", m_dwPatchServerNum, dwBufNum);
m_dwPatchServerNum = dwBufNum;
return true;
}
else if(!strcmp("/patchdown", s_pszDstCheat[0]))
{
DWORD dwBufNum;
if(m_dwPatchServerNum <= 1)
dwBufNum = 1;
else
dwBufNum = m_dwPatchServerNum - 1;
::StringOutput("Patch Server decreases(%d -> %d)", m_dwPatchServerNum, dwBufNum);
m_dwPatchServerNum = dwBufNum;
return true;
}
else if(!strcmp("/예약", s_pszDstCheat[0]))
{
if(nWordNum > 1)
{
if(!strcmp("The outer block", s_pszDstCheat[1]) && nWordNum == 7)
{
if(_SetReserveExternalClose(atoi(s_pszDstCheat[2]), atoi(s_pszDstCheat[3]), atoi(s_pszDstCheat[4]), atoi(s_pszDstCheat[5]), atoi(s_pszDstCheat[6])))
::StringOutput("Reservations accepted");
else
::StringOutput("Booking time errors");
return true;
}
}
}
else if(!strcmp("/loginstat", s_pszDstCheat[0]))
{
if ( m_bExternalOpen )
::StringOutput("External access status");
else
::StringOutput("External connection error status");
return true;
}
else if(!strcmp("/clientcount", s_pszDstCheat[0]))
{
DWORD dwClientCount = CountAliveConnection();
::StringOutput( "Connection : %d", dwClientCount );
return true;
}
return false;
}
I wanna my client just send the message like "/open" or "close" but i don't know hot to write the code in php or android. anyone can help me to solve my problem?
Edit
I already try use this php code
<?php
$host = "127.0.0.1";
$port = 10001;
$message = "open";
echo "Message To server :".$message;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// connect to server
$result = socket_connect($socket, $host, $port) or die("Could not connect to server\n");
// send string to server
socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
// get server response
$result = socket_read ($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server :".$result;
// close socket
socket_close($socket);
?>
and the respon in my browser like this http://prntscr.com/dqje54 and in my server app not recieve the message /open

Related

octave interactive shell using php proc_open

I 'm writing a PHP code to be executed under apache (unfortunately under window OS by using xampp PHP 7.2.x). The PHP script should call an octave in an interactive way in order to be able to execute more commands in sequence without creating for each one a dedicated octave process.
here below an PHP script example.
I have a problem with the interactive working mode; I mean, I'm able to execute an octave script and have back the result but I'm not able to send several octave commands in sequence.
<?php
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a pipe that the child will write to, you can specify a file as well
);
$octave = 'C:\Octave\Octave-4.4.0\bin\octave-cli-4.4.0 ';
$cmd = $octave . ' --no-gui -i -q --eval disp(10)';
$process = proc_open($cmd, $descriptorspec, $pipes);
if (!is_resource($process)) {
die("PROCESS CREATION ERROR CMD: $cmd");
}
$str = "eval('disp(20)');\r\n" . chr(13);
if(fwrite($pipes[0],$str) === false){
die("fwrite ERROR");
}
$str = stream_get_contents($pipes[1]);
if($str === false){
die("stream_get_contents ERROR");
}else{
echo $str;
}
fclose($pipes[0]);
fclose($pipes[1]);
$return_value = proc_close($process);
echo "command returned $return_value\n";
?>
In this case, the output is: 10 commands returned 0
Instead if define $cmd = $octave . ' --no-gui -i -q';
The script is blocked waiting for a returning charter to the stream_get_contents. Same result using fgets.
My understanding is that the fwrite command is not correctly received by an octave and so it doesn't print back the result (even if the fwrite doesn't return any error). Maybe the problem is due to the code to be sent as carriage return in order to tell to octave to execute the code. Moreover, it is not clear, if I should use the eval function or just write the command. However, in all tries done nothing is changed.
Any ideas?
Here below the code review, working if can be useful.
I have also created a dedicated class (octave_stream) in order to provide an interface that permits, for instance, an html pages to start a dedicated octave process ondemand (using a SSE communication) and then send one by one commands as ajax request. The sw will close the octave process whenever the user leave the page or after an unused time.
here below the whole code based on the following 4 files: octave.php, octave_sse.php, octave_com.php.
octave.php
<?php
class octave {
private $pipes = null;
private $process = null;
private $add_semicolon = false;
private $debug = false;
private $print = false;
function __destruct() {
$this->close_octave();
}
public function close_octave(){
if ($this->pipes !== null){
fclose($this->pipes[0]);
fclose($this->pipes[1]);
$return_value = proc_close($this->process);
if($this->debug){ echo "command returned $return_value<br>";}
return $return_value;
}
return false;
}
public function open_octave(){
$dir = sys_get_temp_dir();
$error_file_name = tempnam($dir, "npt");
$descriptorspec = array(
0 => array("pipe", "rb"), // stdin is a pipe that the child will read from
1 => array("pipe", "wb"), // stdout is a pipe that the child will write to
2 => array("file", $error_file_name,"a") // stderr:: you HAVE TO specify a file
);
$octave = 'C:\Octave\Octave-4.4.0\bin\octave-cli-4.4.0 ';
$cmd = $octave . ' --no-gui -i -q';
$pipes = array();
$this->process = proc_open($cmd, $descriptorspec, $pipes);
if (!is_resource($this->process)) {
echo "PROCESS CREATION ERROR CMD: $cmd";
return false;
}
if (count($pipes) == 0){
echo 'pipes: '; var_dump($pipes); echo '<br>';
echo "PROCESS CREATION ERROR CMD: $cmd";
return false;
}
//stream_set_blocking($pipes[1],false); // doesn't work on STDIN / OUT
$this->pipes = $pipes;
$cmd_id = 0;
$this->read($cmd_id);
return true;
} //end open_octave
private function raw_read(){
$str = fread($this->pipes[1],8192);
if($str === false){
echo '<br>'. __FUNCTION__ . ' fgets ERROR for CMD: ' . htmlentities($cmd);
return false;
}
//echo "READ: $str<br>";
return $str;
} //end read
private function read(&$cmd_num){
$result = '';
$string = $this->raw_read();
if($this->debug){echo '<br>' . __FUNCTION__ . ' RAW_READ1: ' . $string; }
if($string[0] == '>'){
//special case, multiple line statement
if($this->debug){echo '<br>' . __FUNCTION__ . ' multiple line statement.' ; }
$cmd_num = -1;
return '';
}
$tok = strtok($string, "octave:");
while (($tok === false) || ($tok == $string)) {
//the response do not conatin the promt; therefore, other rows are coming, read them as well and concatenate to the current response
$result .= $string;
usleep(100);
$string = $this->raw_read();
if($this->debug){echo '<br>' . __FUNCTION__ . ' RAW_READ NEXT: ' . $string; }
$tok = strtok($string, "octave:");
}
$cmd_num = -1;
//in this case string include the promt; nothing more to be read. tok is the string without the "ocatve:" but you still have the 'num>' to be removed.
$allTheRest = strtok( '' );
if(($allTheRest === false) || ($allTheRest == '')){
//tok has the promt rest
list($cmd_num) = sscanf($tok,'%u>');
}else{
$result .= $tok;
list($cmd_num) = sscanf($allTheRest,'ctave:%u>');
}
if($this->debug){echo '<br>' . __FUNCTION__ . " RAW_READ TOK: '$tok' STRING: '$string' RESULT: '$result' allTheRest: '$allTheRest' cmd_num: $cmd_num ## "; }
return $result;
}
//return the command answer removing the promt. Therefore, in case no retrun message command an empty string is given
public function octave_cmd($cmd,&$cmd_num){
if($this->add_semicolon){
$last_chr = strlen($cmd) - 1;
if(substr($cmd, $last_chr, 1) != ';'){
$cmd = $cmd . ';'; // adding ; at the input command required by octave
}
}
//echo "$cmd<br>";exit(0);
$cmd = $cmd . PHP_EOL ;// "\r\n"
if(fwrite($this->pipes[0],$cmd) === false){
echo '<br>'. __FUNCTION__ . ' fwrite ERROR for CMD: ' . htmlentities($cmd);
return false;
}
//usleep(100); // needed when more output row are given ... without this you read before the progam write the next row ... and you lost it ... a nice solution anyway should be to read again unil you find the promt that is always the latest given.
$ret = $this->read($cmd_num);
if($this->print){
echo "<br>COMMAND # $cmd_num: " .htmlentities($cmd) . (($ret != '')?(' RESULT: ' . nl2br(htmlentities($ret))):'') . ' END<br>';
}
return $ret;
}
public function print_cmd($cmd){
$cmd_id = 0;
$ret = $this->octave_cmd($cmd,$cmd_id);
echo "<br>COMMAND # $cmd_id: " .htmlentities($cmd) . (($ret != '')?(' RESULT: ' . nl2br(htmlentities($ret))):'') . ' END<br>';
}
}
class octave_stream {
private $address = 'tcp://127.0.0.1';
private $port = 5454;
private $errno = 0;
private $errstr = '';
private $server_istance = false;
private $sse = false;
/*This function start octave process, open a tcp connection and waits for incoming commands.
(to send the commands use the func. send_cmd)
Each command received is forwared to octave and the ocatve answer is forwared to who sent the command.
To stop the server a special command has to be sent. The caller has to use the stop_server()
*/
public function create_server($accept_max_retray = 30){
$this->server_istance = true; // first command to be done
$available_port = $this->find_usable_listening_port($this->port);
if($available_port === false){
$this->server_log('NOT FOUND AN AVAILABLE PORT TO START THE LISTENING SERVER');
return false;
}else{
$this->port = $available_port;
}
$oct_obj = new octave();
if(!$oct_obj->open_octave()){
return false;
}
$this->server_log('OCTAVE PROCESS STARTED');
$cmd_id = 0;
$server_socket_address = 'tcp://127.0.0.1:' . $this->port;
$socket = stream_socket_server($server_socket_address, $errno, $errstr);
if (!$socket) {
$this->errstr = "$errstr ($errno)<br />\n";
$this->errno = $errno;
$oct_obj->close_octave();
$this->server_log("<b>LISTENING SOCKET CREATION ERROR: $this->errstr</b>");
return false;
}
$exit = false;
$this->server_log("LISTENING SOCKET CREATED: $server_socket_address DEFAULT SOCKET TIMEOUT:" . ini_get("default_socket_timeout"));
$this->server_log($server_socket_address,'server_ready'); // dedicated event type sent, html page has a dedicated event listener on it
$accept_retray = -1;
$conn_id = 0;
do{
$accept_retray += 1;
while ($conn = stream_socket_accept($socket)) {
$this->server_log("LISTENING SOCKET CONNECTION ACCEPTED: $conn_id");
$accept_retray = -1;
//cmd: received octave command request to be sent to octave
$cmd = '';
$cmd = fread($conn,8192);
if($cmd === false){
$this->server_log( __FUNCTION__ . "[$conn_id] fread ERROR for CMD: " . htmlentities($cmd));
return false;
}
$this->server_log("[$conn_id] RECEIVED RAW COMMAND: $cmd");
if(strpos($cmd, '#exit#') !== false){
//special command EXIT
$this->server_log("[$conn_id] RECEIVED EXIT COMMAND.");
fwrite($conn,self::prefix($conn_id) . 'RECEIVED EXIT COMMAND.'); // you need always to send an answer to the calling (it is waiting on read it
$exit = true;
}else if (strpos($cmd, '#loopback:') !== false) {
//special command LOOPBACK
$this->server_log("[$conn_id] RECEIVED LOOPBACK COMMAND: $cmd");
fwrite($conn,self::prefix($conn_id) . $cmd); // you need always to send an answer to the calling (it is waiting on read it
} else {
//OCATVE COMMAND
$this->server_log("[$conn_id] RECEIVED COMMAND FOR OCTAVE: $cmd");
$cmd_id = 0;
$ret = $oct_obj->octave_cmd($cmd,$cmd_id);
$this->server_log("[$conn_id] COMMAND # $cmd_id: " .htmlentities($cmd) . (($ret != '')?(' RESULT: ' . nl2br(htmlentities($ret))):'') . ' END<br>');
fwrite($conn,self::prefix($conn_id) . 'RESULT:'. $ret);
$this->server_log("[$conn_id] SENT ANSWER: RESULT:". $ret);
}
fclose($conn);
$this->server_log("[$conn_id] CLOSE CONNECTION");
$conn_id++;
if($exit) break;
}
if($exit) break;
//note, calling the server_log func here you are testing the socket between this script and the html pages. If the sse connection is no more working, the PHP engine will close this script.
$this->server_log("LISTENING SOCKET CONNECTION TIMEOUT RETRAY: $accept_retray MAX_RETRAY: $accept_max_retray");
}while($accept_retray < $accept_max_retray);
$this->server_log($server_socket_address,'server_stopped'); // dedicated event type sent
fclose($socket);
$this->server_log('SOCKET CLOSED.');
unset($oct_obj);
$this->server_log('OCTAVE PROCESS STOPPED.');
return true;
} // end start_server
private static function prefix($conn_id){
return "[$conn_id] [" . date('n/j/Y g:i:s a') .'] ';
}
//return the ocatve command answer to be encoded e.g. json to be delivered to the http page or false
public function send_cmd($cmd){
if($this->server_istance){
$this->errstr = '<br>'. __FUNCTION__ . ' SERVER ISTANCE.';
return false;
}
$ret = '';
$fp = stream_socket_client($this->address . ':' .$this->port , $errno, $errstr, 30);
if ($fp === false) {
$this->errstr = "$errstr ($errno)<br />\n";
$this->errno = $errno;
return false;
} else {
//fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n");
fwrite($fp, $cmd);
while (!feof($fp)) {
$ret .= fgets($fp, 1024);
}
fclose($fp);
}
return $ret;
} // end send_cmd
//return false or the server answer
public function stop_server(){
if($this->server_istance){
$this->errstr = '<br>'. __FUNCTION__ . ' SERVER ISTANCE.';
$this->errno = 0;
return false;
}
return $this->send_cmd('#exit#');
} //
//return false or the server answer
public function loopback_msg($msg){
if($this->server_istance){
$this->errstr = '<br>'. __FUNCTION__ . ' SERVER ISTANCE.';
$this->errno = 0;
return false;
}
return $this->send_cmd('#loopback:' . $msg);
}
public function get_errstr(&$errno){
$ret = $this->errstr;
$this->errstr = '';
$errno = $this->errno;
$this->errno = 0;
return $ret;
}
//$ip_name: IP or dns name
public function set_address_connection($ip_name,$port){
$this->address = 'tcp://' . $ip_name ;
$this->port = $port;
}
//str can be encoded as json if you need to transfert more data field.
//see: https://www.html5rocks.com/en/tutorials/eventsource/basics/
private function server_log($str,$event_name = ''){
$msg = '<br>[' . date('n/j/Y g:i:s a') .'] '. $str ;
if($this->sse){
if($event_name != ''){
echo "event: $event_name" . PHP_EOL;
echo "data: $str" . PHP_EOL;
}else{
echo "data: $msg" . PHP_EOL;
}
echo PHP_EOL;
}else{
echo $msg;
}
ob_flush();
flush();
}
public function set_sse($sse){
$this->sse = $sse;
}
private function check_server_running_on_port($port,&$ret_errstr,&$errno){
if(!$this->server_istance){
$ret_errstr = '<br>'. __FUNCTION__ . ' REQUIRED SERVER ISTANCE.';
$errno = 0;
return false;
}
$ret_errstr ='';
$errno = 0;
$msg = __FUNCTION__ . ' PORT CHECK: ' . $port;
$cmd = '#loopback:' . $msg; // you cannot change it, is the defined loopback command
$fp = stream_socket_client($this->address . ':' .$port , $errno, $errstr, 30);
if ($fp === false) {
$ret_errstr = "$errstr ($errno)<br />\n";
return false;
}
fwrite($fp, $cmd);
while (!feof($fp)) {
$ret .= fgets($fp, 1024);
}
fclose($fp);
return true;
}
private function find_usable_listening_port($start_port){
if(!$this->server_istance){
$this->errstr = '<br>'. __FUNCTION__ . ' REQUIRED SERVER ISTANCE.';
$this->errno = 0;
return false;
}
$ret_errstr ='';
$errno = 0;
$max_port = $start_port +10;
$port = $start_port;
do{
//ret = true server running, so I need to find another unused port
$ret = $this->check_server_running_on_port($port,$ret_errstr,$errno);
if($ret){
$this->server_log("CHECK USABLE LISTENING PORT: PORT=$port ALREADY USED.");
}else{
$this->server_log("CHECK USABLE LISTENING PORT: PORT=$port NOT USED. GIVEN ERROR: $ret_errstr" );
return $port;
}
$port++;
if($port > $max_port) return false;
}while($ret);
return false;
}
} // end class
?>
octave_sse.php
<?php
/* this page should be called by the web page as sse
this page calling the create_server func start the octave process and the communication server as well.
The function return only when the exit command is received over the server channel created.
Then the page has to send a polling to the web page to test the presence of the page itself.
*/
function sendMsg($sse,$msg) {
if($sse){
echo "data: $msg" . PHP_EOL;
echo PHP_EOL;
}else{
echo $msg;
}
ob_flush();
flush();
}
$sse = false;
if(isset($_GET['sse'])){
if($_GET['sse'] > 0){
$sse = true;
}
}
if($sse){
header('Content-Type: text/event-stream');
}else{
header( 'Content-type: text/html; charset=utf-8' );
}
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
require 'octave.php';
set_time_limit(4000);
$oct_server_obj = new octave_stream();
if($sse){
$oct_server_obj->set_sse(true);
}
sendMsg($sse,'<br>[' . date('n/j/Y g:i:s a') .'] CALLING create_server.<br>');
$ret = $oct_server_obj->create_server();
sendMsg($sse,'<br>[' . date('n/j/Y g:i:s a') .'] create_server EXIT. return: '. (($ret)?'TRUE':'FALSE').'<br>');
//you are here only at the end when the web page send the exit command to the created server
do{
sleep(2);
sendMsg($sse,'<br>[' . date('n/j/Y g:i:s a') .'] create_server PING<br>');
}while(true);
?>
octave_com.php
<?php
/*
This page is called using a json post request from web page.
Each request has a octave command. special param is to terminate the server.
*/
/** Error reporting: this is not used since you are using myErrorHandler */
if($_SERVER['SERVER_NAME'] == "localhost"){ // my PC
error_reporting(E_ALL);
}else{
error_reporting(E_ERROR | E_PARSE);
}
//http://php.net/manual/it/errorfunc.configuration.php#ini.display-errors
/* The errors are redirect over the stderr and not over the stdout.
In this way, you have to properly send the error using json without using the set_error_handler.
ini_set('display_errors','Off');
//ini_set('display_errors','On');
*/
function myErrorHandler ($errno, $errstr, $errfile, $errline) {
if (0 === error_reporting()) { return false;}
$errorType = array (
E_ERROR => 'ERROR',
E_WARNING => 'WARNING',
E_PARSE => 'PARSING ERROR',
E_NOTICE => 'NOTICE',
E_CORE_ERROR => 'CORE ERROR',
E_CORE_WARNING => 'CORE WARNING',
E_COMPILE_ERROR => 'COMPILE ERROR',
E_COMPILE_WARNING => 'COMPILE WARNING',
E_USER_ERROR => 'USER ERROR',
E_USER_WARNING => 'USER WARNING',
E_USER_NOTICE => 'USER NOTICE',
E_STRICT => 'STRICT NOTICE',
E_RECOVERABLE_ERROR => 'RECOVERABLE ERROR');
// create error message
if (array_key_exists($errno, $errorType)) {
$err = $errorType[$errno];
} else {
$err = 'CAUGHT EXCEPTION';
}
if($_SERVER['SERVER_NAME'] != "localhost"){ // not my PC
if (!($errorType == E_ERROR ) || ($errorType == E_PARSE ))
return;
}
$str_err = "$err($errno) <br> in line: " .$errline. " of file: " .$errfile . " <br> PHP: " . PHP_VERSION . " (". PHP_OS .")<br> $errstr";
terminate($str_err);
} // end myErrorHandler
// configura il gestore dell'errore definito dall'utente
$old_error_handler = set_error_handler("myErrorHandler");
// functions
function terminate($str_err, $txt=false){
if($txt){
die($str_err);
}
header("Content-Type: application/json;charset=utf-8");
echo json_encode(array("result"=>"false","error"=>$str_err));
exit(0);
} // end terminate
require 'octave.php';
if(isset($_POST['send_loopback'])){
if(!isset($_POST['message'])){
terminate("message not present!");
}else{
$message = $_POST['message'];
}
$address = '';
$ip='';
$port = 0;
if(isset($_POST['address'])){
$address = $_POST['address'];
$pos = strrpos($address,':');
$ip = substr($address,6,$pos-6);
$port = substr($address,$pos+1);
}
$oct_server_obj = new octave_stream();
//it is supposed to have the server already running ready to manage the sent messages here below
//echo '<br>[' . date('n/j/Y g:i:s a') .'] SEND THE LOOPBACK MESSAGE.<br>';
if($ip != '' and is_numeric($port)){
$oct_server_obj->set_address_connection($ip,$port);
}
$msg = $oct_server_obj->loopback_msg($message);
if($msg === false){
$errno = 0;
terminate($oct_server_obj->get_errstr($errno));
}
echo json_encode(array('result' => 'true', 'error' => '', 'loopback_msg' => $msg)) ;
exit(0);
} // end send_loopback
if(isset($_POST['send_octave_msg'])){
if(!isset($_POST['message'])){
terminate("message not present!");
}else{
$message = $_POST['message'];
}
$address = '';
$ip='';
$port = 0;
if(isset($_POST['address'])){
$address = $_POST['address'];
$pos = strrpos($address,':');
$ip = substr($address,6,$pos-6);
$port = substr($address,$pos+1);
}
$oct_server_obj = new octave_stream();
//it is supposed to have the server already running ready to manage the sent messages here below
//echo '<br>[' . date('n/j/Y g:i:s a') .'] SEND THE LOOPBACK MESSAGE.<br>';
if($ip != '' and is_numeric($port)){
$oct_server_obj->set_address_connection($ip,$port);
}
$msg = $oct_server_obj->send_cmd($message);
if($msg === false){
$errno = 0;
terminate($oct_server_obj->get_errstr($errno));
}
$pos = strpos($msg,'RESULT:');
$ret = trim(substr($msg,$pos+strlen('RESULT:')));
$ret = nl2br(htmlentities($ret));
echo json_encode(array('result' => 'true', 'error' => '', 'msg' => $msg, 'return' => $ret)) ;
exit(0);
} // end send_octave_msg
if(isset($_GET['send_exit_msg'])){
$address = '';
$ip='';
$port = 0;
if(isset($_GET['address'])){
$address = $_GET['address'];
$pos = strrpos($address,':');
$ip = substr($address,6,$pos-6);
$port = substr($address,$pos+1);
}
$oct_server_obj = new octave_stream();
//it is supposed to have the server already running ready to manage the sent messages here below
//echo '<br>[' . date('n/j/Y g:i:s a') .'] SEND THE LOOPBACK MESSAGE.<br>' . "ADDRESS: $address IP: $ip PORT: $port<br>" ;
if($ip != '' and is_numeric($port)){
$oct_server_obj->set_address_connection($ip,$port);
}
$msg = $oct_server_obj->stop_server();
if($msg === false){
$errno = 0;
terminate($oct_server_obj->get_errstr($errno));
}
echo json_encode(array('result' => 'true', 'error' => '', 'return' => $msg)) ;
exit(0);
} // end send_exit_msg
?>
The html web page to be used together with the above code.
octave_shell.html:
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="../../jquery/jqueryui/jquery-ui-1.11.3.custom/jquery-ui.css">
<link rel="stylesheet" href="../../libs/messi/messi.min.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="../../jquery/jqueryui/jquery-ui-1.11.3.custom/jquery-ui.js"></script>
<script src="../../libs/messi/my_messi.min.js"></script>
<script src="../../libs/chosen/chosen.jquery.min.js"></script>
<title>OCTAVE SHELL</title>
</head>
<body>
<h2>OCTAVE WEB INTERFACE</h2>
<script type="text/javascript">
var server_ready = false; // true, octave process running and ready to accept commands
var sse_source; // sse_obj
var octave_close_req = false; // true when the user stop octave
var address = ''; //address on which the server is in listening for commands at server side
function clearArray(array_tbc){
array_tbc.splice(0,array_tbc.length); // set the array to empty
array_tbc.length = 0;
}
function isParamExist(paramName){
if($.inArray(paramName,Object.getOwnPropertyNames(urlParams)) > -1){
console.log("isParamExist:" + paramName + " return TRUE");
return true;
}
console.log("isParamExist:" + paramName + " return FALSE");
return false;
} //end isParamExist
function getParam(urlParams) {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
console.log(Object.getOwnPropertyNames(urlParams));
} //end getParam
function octave_close(){
octave_close_req = true;
$.getJSON('octave_com.php',
{send_exit_msg: 1,
address: address},
function(data) {
if(data.result == "true"){
$('#octave_shell').append("<p><b>"+ data.return +"</b></p>" );
}else{
//alert("Error : " + data.error);
new Messi('Error : ' + data.error, {title: 'ERROR from JSON', titleClass: 'anim error', buttons: [{id: 0, label: 'Close', val: 'X'}]});
}
}
);
} //end octave_close
function ping_server(){
var message = 'HELLO!';
$.post( "octave_com.php",
{ send_loopback: 1,
address: address,
message: message } ,
function( data ) {
if(data.result == 'true'){
var msg = data.loopback_msg;
$('#octave_shell').append("<p><b>"+ msg +"</b></p>" );
}else{
var err = data.error;
new Messi("LOOPBACK ERROR: err: " + err, {title: 'LOOPBACK MESSAGE', titleClass: 'anim warning', buttons: [{id: 0, label: 'Close', val: 'X'}]});
}
},
"json");
} //end ping_server
function send_octave_cmd(cmd){
$.post( "octave_com.php",
{ send_octave_msg: 1,
address: address,
message: cmd } ,
function( data ) {
if(data.result == 'true'){
var msg = data.return;
if(msg == '') msg = 'OK';
$('#octave_shell').append("<p>OCTAVE ANSWER: " + msg + "</p>");
console.log('OCTAVE MESSAGE: ' + data.msg);
}else{
var err = data.error;
new Messi("OCTAVE COMMAND: err: " + err, {title: 'OCTAVE COMMAND ERROR', titleClass: 'anim warning', buttons: [{id: 0, label: 'Close', val: 'X'}]});
}
},
"json");
} //end send_octave_cmd
$(function(){
if(typeof(EventSource) !== "undefined") {
sse_source = new EventSource("octave_sse.php?sse=1");
sse_source.onmessage = function(event) {
console.log('SSE MSG: ' + event.data);
document.getElementById("sse_log").innerHTML += event.data + "<br>";
};
sse_source.addEventListener('open', function(e) {
// Connection was opened.
console.log('SSE OPEN.');
document.getElementById("sse_log").innerHTML += 'SSE OPEN.' + "<br>";
}, false);
sse_source.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED) {
// Connection was closed.
server_ready = false;
console.log('SSE CLOSED.');
document.getElementById("sse_log").innerHTML += 'SSE CLOSED.' + "<br>";
}
}, false);
//user defined event types
sse_source.addEventListener('server_ready', function(e) {
// server_ready event received.
server_ready = true;
address = e.data;
console.log('SSE server_ready EVENT ADDR: ' + address);
$('#octave_status').text('SERVER READY TO ACCEPT OCTAVE COMMANDS ON: '+ address);
}, false);
sse_source.addEventListener('server_stopped', function(e) {
// server_stopped event received.
server_ready = false;
console.log('SSE server_stopped EVENT');
setTimeout(function(){ sse_source.close(); }, 3000); //close the sse connection as well, you don't need anymore.
if(!octave_close_req){
$('#octave_status').text('SERVER HAS BEEN CLOSED FOR TIMEOUT. RE-LOAD THE PAGE TO START A NEW WORKING SESSION.');
new Messi(
'OCTAVE PROCESS STOPPED FOR TIMEOUT. RE-LOAD THE PAGE TO START A NEW WORKING SESSION.',
{
title: 'OCTAVE PROCESS STOPPED',
titleClass: 'anim info',
buttons: [ {id: 0, label: 'Close', val: 'X'} ]
}
);
}else{
$('#octave_status').text('SERVER HAS BEEN CLOSED FOR USER DECISION. RE-LOAD THE PAGE TO START A NEW WORKING SESSION.');
new Messi(
'YOU HAVE CLOSED CORRECTLY THE OCTAVE PROCESS. RE-LOAD THE PAGE TO START A NEW WORKING SESSION.',
{
title: 'OCTAVE PROCESS STOPPED',
titleClass: 'anim info',
buttons: [ {id: 0, label: 'Close', val: 'X'} ]
}
);
}
}, false);
} else {
alert('NO SSE SUPPORT. Please do not use an obsolete browser!');
}
$('#close_octave_id').click(function() {
console.log('CLOSE OCTAVE REQUEST');
octave_close();
});
$('#send_ping_id').click(function() {
console.log('PING DISPATCHER SERVER REQUEST');
ping_server();
});
$('#send_octave_cmd_id').click(function() {
var cmd = $('#write_octave_cmd_id').val();
//console.log('SEND OCTAVE CMD REQUEST: ' + cmd);
$('#octave_shell').append("<p>OCTAVE: " + cmd + "</p>");
send_octave_cmd(cmd);
$('#write_octave_cmd_id').val('');
});
$('#write_octave_cmd_id').keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{
$('#send_octave_cmd_id').click();
return false;
}
});
//getParam(urlParams);
/*
if(!isParamExist('json_file_net_name')){
//load the NPT results
loadNPTData();
}else{
// load DESIGN results
loadJSONData();
}
*/
}); // end startup page
</script>
<div id='octave_cmd'>
<h4>Write your OCTAVE commands here, press enter or click on SEND OCTAVE CMD to execute them.<br>
<b>IMPORTANT: </b>Don't forget to terminate the commands with semicolon as per OCTAVE syntax.</h4>
<br><p>Some example commands: disp(10) just to print 10,<br>
to solve a non linear system equation writes the following commands line by line pressing enter for each row:<br>
<i>function y = test6(x)<br>
y(1) = 18.028*cosd(x(1))+10*cosd(45)-15*cosd(x(2))<br>
y(2) = 18.028*sind(x(1))+10*sind(45)-15*sind(x(2))<br>
endfunction<br>
[x, fval, info] = fsolve(#test6, [0;0]);<br>
disp(x);<br>
disp(info);</i><br>
</p><br>
</div><br>
<br><a href='#' id='close_octave_id' >CLOSE OCTAVE - CLICK WHEN YOU HAVE TERMINATED.</a><br>
<br><a href='#' id='send_ping_id' >PING DISPATCHER SERVER </a><br>
<div id='octave_status'></div>
<br><div id='octave_shell'><h4>OCTAVE SHELL:</h4><br></div><br>
<input type='text' id='write_octave_cmd_id' size="400"><br>
<a href='#' id='send_octave_cmd_id' >SEND OCTAVE CMD</a>
<br><div id='sse_log'><h4>SSE LOG:</h4><br></div><br>
</body>
</html>

socket_connect() not work with 25 port

I try to write code for email verify like that
But i have one problem, 25 port not connect with any mail server
My code like that
Example.php
<?php
require('smtp-validate-email.php');
$from = 'harsukh21#gmail.com'; // for SMTP FROM:<> command
$emails = 'harsukh#gmail.com';
$validator = new SMTP_Validate_Email($emails, $from);
$smtp_results = $validator->validate();
echo "<pre>";print_r($smtp_results);exit;
smtp-validate-email.php
<?php/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. *//** * Description of EmailValidation * * #author Harsukh Makwana <harsukh21#gmail.com> */class EmailValidation{ public $hellodomain = 'itsolutionstuff.com'; public $mailfrom = 'harsukh21#gmail.com'; public $rcptto; public $mx; public $ip; public function __construct() { $this->ip = '192.168.2.14'; } public function checkEmail($email = null) { $this->rcptto = $email; $array = explode('#', $this->rcptto); $dom = $array[1]; if (getmxrr($dom, $mx)) { $this->mx = $mx[rand(0, count($mx) - 1)]; return $this->processRange($this->ip); } return false; } private function asyncRead($sock) { $read_sock = array($sock); $write_sock = NULL; $except_sock = NULL; if (socket_select($read_sock, $write_sock, $except_sock, 5) != 1) { return FALSE; } $ret = socket_read($sock, 512); return $ret; } private function smtpConnect($mta, $src_ip) { $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($sock == FALSE) { return array(FALSE, 'unable to open socket'); } if (!socket_bind($sock, $src_ip)) { return array(FALSE, 'unable to bind to src ip'); } $timeout = array('sec' => 10, 'usec' => 0); socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, $timeout); socket_set_nonblock($sock); var_dump(#socket_connect($sock, $mta, 25));exit; #socket_connect($sock, $mta, 25); $ret = $this->asyncRead($sock); if ($ret === FALSE) { return array(FALSE, 'inital read timed out'); } if (!preg_match('/^220/', $ret)) { // Not a good connection. return array(FALSE, $ret); } // Now do the EHLO. socket_write($sock, "HELO ".$this->hellodomain."\r\n"); $ret = $this->asyncRead($sock); if ($ret === FALSE) { return array(FALSE, 'ehlo timed out'); } if (!preg_match('/^250/', $ret)) { // Not a good response. return array(FALSE, $ret); } // Now MAIL FROM. socket_write($sock, "MAIL FROM:<".$this->mailfrom.">\r\n"); $ret = $this->asyncRead($sock); if ($ret === FALSE) { return array(FALSE, 'from timed out'); } if (!preg_match('/^250/', $ret)) // Not a good response. return array(FALSE, $ret); // Now RCPT TO. socket_write($sock, "RCPT TO:<".$this->rcptto.">\r\n"); $ret = $this->asyncRead($sock); if ($ret === FALSE) { return array(FALSE, 'rcpt to timed out'); } if (!preg_match('/^250/', $ret)) { // Not a good response. return array(FALSE, $ret); } // All good. socket_close($sock); return array(true, $ret); } private function processRange($ip) { list($ret, $msg) = $this->smtpConnect($this->mx, $ip); $msg = trim($msg); return $ret; }}
Output
Array
(
[harsukh#gmail.com] =>
[domains] => Array
(
[gmail.com] => Array
(
[users] => Array
(
[0] => harsukh
)
[mxs] => Array
(
[gmail-smtp-in.l.google.com] => 5
[alt1.gmail-smtp-in.l.google.com] => 10
[alt2.gmail-smtp-in.l.google.com] => 20
[alt3.gmail-smtp-in.l.google.com] => 30
[alt4.gmail-smtp-in.l.google.com] => 40
[gmail.com] => 0
)
)
)
)
Here harsukh#gmail.com is a already exist, But i getting null responce
can i use another port for mail server?
You can't use a port that's already in use. So probebly there is already an email server on the same machine where you are running your code.
can i use another port for mail server?
If you plan to use only clients written by yourself, so that you can change the port to which they send data, that can be acceptable, otherwise no.

Unable to open socket, connection timed out

Trying to sent packages from my webhost to a game server, using this code. However it always results in Unable to open socket: Connection timed out (110) ad I can't figure out why it times out. When I try this on my localhost, it works perfectly but when on webhost, it just times out. I've tried to set the timeout to something else but it didn't help.
define("SERVERDATA_EXECCOMMAND",2);
define("SERVERDATA_AUTH",3);
class RCon {
var $Password;
var $Host;
var $Port = 27015;
var $_Sock = null;
var $_Id = 0;
function RCon ($Host,$Port,$Password) {
$this->Password = $Password;
$this->Host = $Host;
$this->Port = $Port;
$this->_Sock = #fsockopen($this->Host,$this->Port, $errno, $errstr, 30) or
die("Unable to open socket: $errstr ($errno)\n");
$this->_Set_Timeout($this->_Sock,2,500);
}
function Auth () {
$PackID = $this->_Write(SERVERDATA_AUTH,$this->Password);
// Real response (id: -1 = failure)
$ret = $this->_PacketRead();
if ($ret[1]['id'] == -1) {
die("Authentication Failure\n");
}
}
function _Set_Timeout(&$res,$s,$m=0) {
if (version_compare(phpversion(),'4.3.0','<')) {
return socket_set_timeout($res,$s,$m);
}
return stream_set_timeout($res,$s,$m);
}
function _Write($cmd, $s1='', $s2='') {
// Get and increment the packet id
$id = ++$this->_Id;
// Put our packet together
$data = pack("VV",$id,$cmd).$s1.chr(0).$s2.chr(0);
// Prefix the packet size
$data = pack("V",strlen($data)).$data;
// Send packet
fwrite($this->_Sock,$data,strlen($data));
// In case we want it later we'll return the packet id
return $id;
}
function _PacketRead() {
//Declare the return array
$retarray = array();
//Fetch the packet size
while ($size = #fread($this->_Sock,4)) {
$size = unpack('V1Size',$size);
//Work around valve breaking the protocol
if ($size["Size"] > 4096) {
//pad with 8 nulls
$packet = "\x00\x00\x00\x00\x00\x00\x00\x00".fread($this->_Sock,4096);
} else {
//Read the packet back
$packet = fread($this->_Sock,$size["Size"]);
}
array_push($retarray,unpack("V1ID/V1Response/a*S1/a*S2",$packet));
}
return $retarray;
}
function Read() {
$Packets = $this->_PacketRead();
foreach($Packets as $pack) {
if (isset($ret[$pack['ID']])) {
$ret[$pack['ID']]['S1'] .= $pack['S1'];
$ret[$pack['ID']]['S2'] .= $pack['S1'];
} else {
$ret[$pack['ID']] = array(
'Response' => $pack['Response'],
'S1' => $pack['S1'],
'S2' => $pack['S2'],
);
}
}
return $ret;
}
function sendCommand($Command) {
$Command = '"'.trim(str_replace(' ','" "', $Command)).'"';
$this->_Write(SERVERDATA_EXECCOMMAND,$Command,'');
}
function rconCommand($Command) {
$this->sendcommand($Command);
$ret = $this->Read();
//ATM: Source servers don't return the request id, but if they fix this the code below should read as
// return $ret[$this->_Id]['S1'];
return $ret[0]['S1'];
}
}
If I specify udp connection in fsockopen it does not timeout, however if I try tcp, it times out. Most likely caused by the host, but I have no idea where to go from this.
https://developer.valvesoftware.com/wiki/Source_RCON_Protocol
https://developer.valvesoftware.com/wiki/Server_queries

How to print Carrier Return and Line Feed in Data Matrix with .prn file in PHP

I need print a DataMatrix with Carrier Return and Line Feed.
My printer its a Zebra GK420t.
I make the label in Zebra Designer and when the label is printed from Zebra Designer the CR and LF works, but when i export the label to a PRN file, to print with PHP, the CR and LF not working.
PHP Code
<?php
class ZebraBarcode {
var $host = "";
var $port = "";
var $error = "";
var $prn = "";
function __construct($host,$port) {
$this->host = $host;
$this->port = $port;
$this->prn = "CT~~CD,~CC^~CT~
^XA~TA000~JSN^LT0^MNW^MTT^PON^PMN^LH0,0^JMA^PR2,2~SD30^JUS^LRN^CI0^XZ
^XA
^MMT
^PW799
^LL0400
^LS0
^FO4,4^GB795,396,8^FS
^FO5,197^GB794,101,8^FS
^FT642,236^A0N,25,26^FH\^FDCANTIDAD^FS
^FT275,67^A0N,37,52^FH\^FDMEMORIA GRABADA^FS
^FT587,328^A0N,28,28^FH\^FDLOTE^FS
^FT355,328^A0N,28,28^FH\^FDPANEL^FS
^FT22,329^A0N,28,28^FH\^FDMODELO^FS
^FT30,236^A0N,25,26^FH\^FDSEMIELABORADO^FS
^FT34,122^A0B,25,24^FH\^FDEBS^FS
^FT34,277^A0N,34,33^FH\^FD4-651-IAPOWTV00148^FS
^FT587,381^A0N,39,38^FH\^FDL104^FS
^FT355,380^A0N,39,38^FH\^FDHIR^FS
^FT21,381^A0N,39,38^FH\^FD32LD846HT^FS
^FT294,165^A0N,90,88^FH\^FDOP-84366^FS
^FT613,283^A0N,42,69^FH\^FD99000^FS
^BY160,160^FT53,187^BXN,5,200,0,0,1,_
^FH\^FDOP-84188\0D\0A4-651-IAPOWTV00148\0D\0APLA\0D\0A99000\0D\0A100\0D\0AP3-UshZebra3^FS
^FO15,333^GB773,0,6^FS
^FO575,299^GB0,92,4^FS
^FO344,299^GB0,92,4^FS
^LRY^FO593,208^GB0,79,7^FS^LRN
^LRY^FO582,300^GB206,0,31^FS^LRN
^LRY^FO351,300^GB222,0,32^FS^LRN
^LRY^FO602,208^GB185,0,34^FS^LRN
^LRY^FO16,300^GB325,0,32^FS^LRN
^LRY^FO264,26^GB470,0,54^FS^LRN
^LRY^FO17,208^GB222,0,34^FS^LRN
^LRY^FO14,14^GB0,180,23^FS^LRN
^PQ1,0,1,Y^XZ
";
}
function Imprimir(){
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
$this->error = "socket_create() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
return false;
}
$result = socket_connect($socket, $this->host, $this->port);
if ($result === false) {
$this->error = "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
return false;
}
socket_write($socket, $this->prn, strlen($this->prn));
socket_close($socket);
return true;
}
}
$o = new ZebraBarcode("10.30.30.128",9100);
$o->Imprimir();
?>
The code works!!,but CR and LF still not working. Any ideas?
Thanks in advance!
Hex values normally are escaped with an _ (underscore).
Try _0D_0A instead of \0D\0A!

C++ and PHP socket connection

I'd like to connect to my c++ server using php...
So far, i got:
Server.cpp
#include <winsock2.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
WSADATA wsaData;
SOCKET mySocket;
SOCKET myBackup;
SOCKET acceptSocket;
sockaddr_in myAddress;
// setup WSA and socket....
if( WSAStartup( MAKEWORD(2, 2), &wsaData ) != NO_ERROR )
{
cerr<<"Socket Initialization: Error with WSAStartup\n";
system("pause");
WSACleanup();
exit(10);
}
//Create a socket
mySocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( mySocket == INVALID_SOCKET )
{
cerr<<"Socket Initialization: Error creating socket"<<endl;
system("pause");
WSACleanup();
exit(11);
}
myBackup = mySocket;
//bind
myAddress.sin_family = AF_INET;
myAddress.sin_addr.s_addr = inet_addr( "0.0.0.0" );
myAddress.sin_port = htons( 25555 );
if ( bind ( mySocket, (SOCKADDR*) &myAddress, sizeof( myAddress) ) == SOCKET_ERROR )
{
cerr<<"ServerSocket: Failed to connect\n";
system("pause");
WSACleanup();
exit(14);
}
//listen
if ( listen ( mySocket, 10 ) == SOCKET_ERROR )
{
cout<<"ERR: ServerSocket: Error listening on socket\n";
system("pause");
WSACleanup();
exit(15);
}
cout<<"srv started. listeninig...\n";
//accept
acceptSocket = accept( myBackup, NULL, NULL );
while ( acceptSocket == SOCKET_ERROR )
{
acceptSocket = accept( myBackup, NULL, NULL );
}
mySocket = acceptSocket;
cout<<"done.\n";
return 0;
}
and the php client
<?php
$port = 25555;
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
#socket_bind($socket,'',$port);
socket_connect($socket, '/my_ip/', $port);
echo 'connecting...';
?>
I dont know what to do. the c++ server just cant see php client...
You need the correct checks in PHP to make sure everything worked.
Try this:
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
die("socket_create() failed: Reason: " . socket_strerror(socket_last_error()) . "\n\n");
return false;
}
echo("Attempting to connect to '{$IP}' on port '{$PORT}'");
$result = socket_connect($socket, $IP, $PORT);
if ($result === false) {
echo("socket_connect() failed. Reason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n\n");
return false;
} else {
echo "OK.\n\n";
}
check error codes...
socket_create
socket_create() returns a socket resource on success, or FALSE on error.
and
socket_connect
Returns TRUE on success or FALSE on failure.
The error code can be retrieved with socket_last_error().
This code may be passed to socket_strerror() to get a textual explanation of the error.

Categories