Connecting to PHP using telnet and sending data to the same port using Java
Hi there! Have been busy busy busy. What I needed was a way to the following;
Above you are looking at a very simple layout. ( Almost childishly simple ) The embedded device has Linux installed with a supposedly very light JVM ( Java Virtual Machine ) So if I am to send data to and from the server and display it to the user I have to do some scripting both in Java and in PHP. Let us first take a look at our universal Java-Socket program which basically opens and listens to a certain port (socket );
import java.io.*;
import java.net.*;
//This program will listen to port 8189
public class ThreadedEchoServer{
public static void main (String[] args){
try{
int i =1;
ServerSocket s = new ServerSocket(8189);
for (;;)
{
Socket incoming = s.accept( );
System.out.println("Spawning " + i);
Thread t = new ThreadedEchoHandler(incoming, i);
t.start();
i++;
}
}catch (Exception e){
e.printStackTrace();
}
}
}
/**
This class handles the client input for one server socket
connection.
*/
class ThreadedEchoHandler extends Thread
{
/**
Constructs a handler.
@param i the incoming socket
@param c the counter for the handlers (used in prompts)
*/
public ThreadedEchoHandler(Socket i, int c)
{
incoming = i; counter = c;
}
public void run()
{
try
{
BufferedReader in = new BufferedReader
(new InputStreamReader(incoming.getInputStream()));
PrintWriter out = new PrintWriter
(incoming.getOutputStream(), true /* autoFlush */);
out.println( "Hello! Enter BYE to exit." );
boolean done = false;
while (!done)
{
String str = in.readLine();
if (str == null) done = true;
else
{
// out.println("Echo (" + counter + "): " + str);
out.println("Connected to : " + str + "<br/>");
//this is where you get the dang str!!! that is sent by embedded device.
//OR this is where you get the configurations from php server on the embedded device.
System.out.println("Php server sent the following string :"+str);
if (str.trim().equals("BYE"))
done = true;
}
}
incoming.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
private Socket incoming;
private int counter;
}
So we have finished with the Java code. Which both can be installed in the server or the embedded device. Notice that the port is 8189. Let us assume that this nice piece of work is on the embedded device. Now we have to send commands to and from the device via PHP using a telnet like protocol. That is when I started searching Google. Came up with a nice site http://www.geckotribe.com/php-telnet/
A nice site if you want to send data to and from telnet. And indeed it was what I needed. However I needed to do some modifications to the code they provided. The code below belongs to them;
(PHPTelnet.php)
<?php
/*
PHPTelnet
*/
class PHPTelnet {
var $show_connect_error=1;
var $use_usleep=1; // change to 1 for faster execution default:0
// don't change to 1 on Windows servers unless you have PHP 5
var $sleeptime=125000;
var $loginsleeptime=1000000;
var $fp=NULL;
var $loginprompt;
var $conn1;
var $conn2;
/*
0 = success
1 = couldn't open network connection
2 = unknown host
3 = login failed
4 = PHP version too low
*/
function Connect($server,$user,$pass) {
$rv=0;
$vers=explode('.',PHP_VERSION);
$needvers=array(4,3,0);
$j=count($vers);
$k=count($needvers);
if ($k<$j) $j=$k;
for ($i=0;$i<$j;$i++) {
if (($vers[$i]+0)>$needvers[$i]) break;
if (($vers[$i]+0)<$needvers[$i]) {
$this->ConnectError(4);
return 4;
}
}
$this->Disconnect();
if (strlen($server)) {
if (preg_match('/[^0-9.]/',$server)) {
$ip=gethostbyname($server);
if ($ip==$server) {
$ip='';
$rv=2;
}
} else $ip=$server;
} else $ip='127.0.0.1';
if (strlen($ip)) {
if ($this->fp=fsockopen($ip,8189))
{
if( ($user!="")&& ($pass!=""))
{
fputs($this->fp,$this->conn1);
$this->Sleep();
fputs($this->fp,$this->conn2);
$this->Sleep();
$this->GetResponse($r);
$r=explode("n",$r);
$this->loginprompt=$r[count($r)-1];
fputs($this->fp,"$userr");
$this->Sleep();
fputs($this->fp,"$passr");
if ($this->use_usleep) usleep($this->loginsleeptime);
else sleep(1);
$this->GetResponse($r);
$r=explode("n",$r);
if (($r[count($r)-1]=='')||($this->loginprompt==$r[count($r)-1])) {
$rv=3;
$this->Disconnect();
}
}
} else $rv=1;
}
if ($rv) $this->ConnectError($rv);
return $rv;
}
function Disconnect($exit=1) {
if ($this->fp) {
if ($exit) $this->DoCommand('exit',$junk);
fclose($this->fp);
$this->fp=NULL;
}
}
function DoCommand($c,&$r) {
if ($this->fp) {
fputs($this->fp,"$cr");
$this->Sleep();
$this->GetResponse($r);
$r=preg_replace("/^.*?n(.*)n[^n]*$/","$1",$r);
}
return $this->fp?1:0;
}
function GetResponse(&$r) {
$r='';
do {
$r.=fread($this->fp,1000);
$s=socket_get_status($this->fp);
} while ($s['unread_bytes']);
}
function Sleep() {
if ($this->use_usleep) usleep($this->sleeptime);
else sleep(1);
}
function PHPTelnet() {
$this->conn1=chr(0xFF).chr(0xFB).chr(0x1F).chr(0xFF).chr(0xFB).
chr(0x20).chr(0xFF).chr(0xFB).chr(0x18).chr(0xFF).chr(0xFB).
chr(0x27).chr(0xFF).chr(0xFD).chr(0x01).chr(0xFF).chr(0xFB).
chr(0x03).chr(0xFF).chr(0xFD).chr(0x03).chr(0xFF).chr(0xFC).
chr(0x23).chr(0xFF).chr(0xFC).chr(0x24).chr(0xFF).chr(0xFA).
chr(0x1F).chr(0x00).chr(0x50).chr(0x00).chr(0x18).chr(0xFF).
chr(0xF0).chr(0xFF).chr(0xFA).chr(0x20).chr(0x00).chr(0x33).
chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0x2C).chr(0x33).
chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0xFF).chr(0xF0).
chr(0xFF).chr(0xFA).chr(0x27).chr(0x00).chr(0xFF).chr(0xF0).
chr(0xFF).chr(0xFA).chr(0x18).chr(0x00).chr(0x58).chr(0x54).
chr(0x45).chr(0x52).chr(0x4D).chr(0xFF).chr(0xF0);
$this->conn2=chr(0xFF).chr(0xFC).chr(0x01).chr(0xFF).chr(0xFC).
chr(0x22).chr(0xFF).chr(0xFE).chr(0x05).chr(0xFF).chr(0xFC).chr(0x21);
}
function ConnectError($num) {
if ($this->show_connect_error) switch ($num) {
case 1: echo '<br />[PHP Telnet] <a href="http://www.geckotribe.com/php-telnet/errors/fsockopen.php">Connect failed: Unable to open network connection</a><br />'; break;
case 2: echo '<br />[PHP Telnet] <a href="http://www.geckotribe.com/php-telnet/errors/unknown-host.php">Connect failed: Unknown host</a><br />'; break;
case 3: echo '<br />[PHP Telnet] <a href="http://www.geckotribe.com/php-telnet/errors/login.php">Connect failed: Login failed</a><br />'; break;
case 4: echo '<br />[PHP Telnet] <a href="http://www.geckotribe.com/php-telnet/errors/php-version.php">Connect failed: Your server's PHP version is too low for PHP Telnet</a><br />'; break;
}
}
}
return;
?>
However because I needed something that used a different port had to change the port number if you look at the comments in the form you will see where I edited the code.
Also because my Telnet was without a password ( i wanted to test it first) I added an “if” statement. Now to the index.php code;
<html><head><title></title></head><body>
<?php
require_once "PHPTelnet.php";
$telnet = new PHPTelnet();
// if the first argument to Connect is blank,
// PHPTelnet will connect to the local host via 127.0.0.1
// the second blank is for the username (may be for embedded device)
// the third blank is for the password (may be for embedded device)
$result = $telnet->Connect('','','');
if ($result == 0) {
$telnet->DoCommand('The embedded device!!', $result);
// NOTE: $result may contain newlines
echo $result;
$telnet->DoCommand('BYE', $result);
echo $result;
// say Disconnect(0); to break the connection without explicitly logging out
$telnet->Disconnect();
}
?>
</body></html>
Now to run a test; first run the Java program ( I hope you know how to compile and run a java program from console.) And than simply open index.php ( of course from Apache! ) And voilà!! you have a program that can connect directly to a php server page!!
Questions? Comments just send it in!