Socket php server not showing messages sent from android client - php

Hi I am a newbie in these kind of stuff but here's what i want to do.
I am trying to implement a chat application in which users will send their queries from the website and as soon as the messages are sent by the website users.It will appear in the android mobile application of the site owner who will answer their queries .In short I wanna implement a live chat.
Now right now I am just simply trying to send messages from android app to php server.
But when I run my php script from dreamweaver in chrome the browser keeps on loading and doesn't shows any output when I send message from the client.
Sometimes it happened that the php script showed some outputs which I have sent from the android(client).But i don't know when it works and when it does not.
So I want to show those messages in the php script as soon as I send those messages from client and vice versa(did not implemented the vice versa for client but help will be appreciated).
Here's what I've done till now.
php script:
<?php
set_time_limit (0);
$address = '127.0.0.1';
$port = 1234;
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($sock, $address, $port) or die('Could not bind to address');
socket_listen($sock);
$client = socket_accept($sock);
$welcome = "Roll up, roll up, to the greatest show on earth!\n? ";
socket_write($client, $welcome,strlen($welcome)) or die("Could not send connect string\n");
do{
$input=socket_read($client,1024,1) or die("Could not read input\n");
echo "User Says: \n\t\t\t".$input;
if (trim($input) != "")
{
echo "Received input: $input\n";
if(trim($input)=="END")
{
socket_close($spawn);
break;
}
}
else{
$output = strrev($input) . "\n";
socket_write($spawn, $output . "? ", strlen (($output)+2)) or die("Could not write output\n");
echo "Sent output: " . trim($output) . "\n";
}
}
while(true);
socket_close($sock);
echo "Socket Terminated";
?>
Android Code:
public class ServerClientActivity extends Activity {
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "127.0.0.1";
private static final int REDIRECTED_SERVERPORT = 1234;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
try
{
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
}
catch (UnknownHostException e1)
{
e1.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try
{
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
}
catch (UnknownHostException e)
{
tv.setText(e.getMessage());
e.printStackTrace();
}
catch (IOException e)
{
tv.setText(e.getMessage());
e.printStackTrace();
}
catch (Exception e)
{
tv.setText(e.getMessage());
e.printStackTrace();
}
}
});
}
}
I've just pasted the onclick button event code for Android.Edit text is the textbox where I am going to enter my text.
The ip address and port are same as in php script.

I'd recommend using an event driven framework for handling your connections.
There's a fairly decent example called React but it has tons of other stuff in there you'll probably want to strip out so your app doesn't depend on hundreds of external components.
React uses a message loop based on libevent if you have it installed, or stream_select otherwise.
You handle events with closures, something like:
$client->on('read', function($data) use ($client) {
$client->onRead($data);
});
With this you will be able to handle lots of simultaneous connections, and it will not tie up all of your CPU.
Your code will be executed when something happens.
If nothing else, have a look at how it works, you'll get a better understanding of how to create a non-blocking event driven socket server.

First of all - your server will handle only one client connection at a time, which doesn't makes sense for chat.
I can't see how you deal with socket connection on Android side but anyway it will not allow you to connect again as long as your script execution will not execute "socket_accept()" and wait for connection.
You should run 1 loop process to grab new client connections and fork into separate process each connected client.
Take look at my same lightweight PHP server I wrote here which is based on the same principle:
https://github.com/webdevbyjoss/Aaaaa---space-ships-combat-multiplayer-game/blob/master/server/server.php
Ignore the Websockets related "doHandshake()" and "WebSocketFrame::decode/WebSocketFrame::encode" but you should be OK with the rest.
Generally it runs the loop
while (true)
if (($msgsock = socket_accept ( $sock )) === false) {
echo "socket_accept() failed: reason: " . socket_strerror ( socket_last_error ( $sock ) ) . "\n";
break;
}
// We got a client connected, lets process it in separate thread
if (($pid = pcntl_fork()) === -1) {
echo "pcntl_fork() failed. Make sure you are on Linux sustem, but not on Windows\n";
break;
}
if (!$pid) { // client
handleClient($msgsock);
exit();
}
// parent server will wait to accept more clients connections in new loop
}
And inside handleClient() function you should have a separate loop to communicate with the client.
while (true) {
if (false === ($buf = socket_read ( $msgsock, 2048, PHP_BINARY_READ ))) {
echo "socket_read() failed: reason: " . socket_strerror ( socket_last_error ( $msgsock ) ) . "\n";
return;
}
if (empty($buf)) { // do disconnection check
echo "Client disconnected\n";
return;
}
// -------------------------------------------------------------
// PUT YOUR BUSINESS LOGIC HERE
// TO HANDLE MESSAGES OF THE CHAT AND GENERATE RESPONSE TO USER
// I RECOMMEND TO USE SOMETHING LIKE MEMCACHE/REDIS/MONGO/MYSQL/TXT-FILES
// FOR MULTIPROCESS DATA INTERCHANGE
// -------------------------------------------------------------
// transfer data to client
socket_write($msgsock, $returnText, strlen($returnFrame));
}
socket_close ( $msgsock );

Have you tried adding '\r\n' into value of EditText before sending to server yet? I think the problem isn't connection between client and server because it doesn't show error when connection fail. Maybe in your case socket_read($client,1024,1) must stop reading at a '\r\n'.
Update: Your local ip maybe cause connection error. Have a look at this link

Your address 127.0.0.1 will resolve to the machine the code is running on. So the app actually tries to connect to itself. type ipconfig /all on the MSDOS console and use that address instead.

Related

Why SMPP bind Transmitter return error 0x34 (ESME_RINVDLNAME)

It`s my first time to write PHP code that sends SMS through
SMPP [Short Message peer to Peer] protocol by onlinecity php-smpp library from gethub URL: **https://github.com/onlinecity/php-smpp**,
I used the code below which sending SMS, but its only response an error
**The return value is error 0x34 (ESME_RINVDLNAME) Invalid Distribution List Name.**
So please help me to resolve this error
<?php
$GLOBALS['SMPP_ROOT'] = dirname(__FILE__); // assumes this file is in the root
require_once $GLOBALS['SMPP_ROOT'].'/protocol/smppclient.class.php';
require_once $GLOBALS['SMPP_ROOT'].'/protocol/gsmencoder.class.php';
require_once $GLOBALS['SMPP_ROOT'].'/transport/tsocket.class.php';
// Simple debug callback
function printDebug($str) {
//echo date('Ymd H:i:s ').$str."\r\n";
}
try {
// Construct transport and client, customize settings
$transport = new TSocket('192.168.111.1',5016,false,'printDebug'); // hostname/ip (ie. localhost) and port (ie. 2775)
//print_r($transport);
$transport->setRecvTimeout(10000);
$transport->setSendTimeout(10000);
$smpp = new SmppClient($transport,'printDebug');
print_r($smpp);
// Activate debug of server interaction
$smpp->debug = true; // binary hex-output
$transport->setDebug(true); // also get TSocket debug
// Open the connection
$transport->open();
$smpp->bindTransmitter("username","password");
// Prepare message
$message = 'Hello world';
$encodedMessage = GsmEncoder::utf8_to_gsm0338($message);
$from = new SmppAddress(GsmEncoder::utf8_to_gsm0338('5672'),SMPP::TON_ALPHANUMERIC);
$to = new SmppAddress('967777841622',SMPP::TON_INTERNATIONAL,SMPP::NPI_E164);
// Send
$smpp->sendSMS($from,$to,$encodedMessage);
//print_r($smpp);
// Close connection
// print_r($smpp);
$smpp->close();
} catch (Exception $e) {
// Try to unbind
try {
$smpp->close();
} catch (Exception $ue) {
// if that fails just close the transport
printDebug("Failed to unbind; '".$ue->getMessage()."' closing transport");
if ($transport->isOpen()) $transport->close();
}
// Rethrow exception, now we are unbound or transport is closed
throw $e;
}
I found this issue belong into SMPP interface version , which php-smpp project from onlinecity on GitHub using v3.4 [0x34] , however, this version is blocked from SMSC.
when I changed the interface version from 3.4 [0x34] into 0.3 [0x03]
code working fine.

Sending send data through URL parameters in Android

I'm trying to make an app when users fill form, and click send button, to send informations through url parametrs like :
localhost/my.php?param1=Name&param2=SureName
I have read through internet about it, but can't get it, I found some examples but they tell how to pass through Json, I want just to send through link. (I think is easiest way )
My php code is:
<?php
require "connection.php";
if (!isset($_GET['param1'])) {
echo '<p align="center"> No data passed!</p>"';
}
if (strcmp($_GET['param1'],'FirstParam')== 0)
{
$sql= "Query HERE TO ADD INTO DB";
mysqli_query($connection,$sql);
if ($connection->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $connection->error;
}
mysqli_close($connection);
}
Any help will be appreciated.
I recommend to have a look on OkHttp. It is an easy library to send HTTP requests in whatever way you like. On Vogella you can also find an example of sending a GET request with additional parameters. Basically it looks like this
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://api.github.help").newBuilder();
urlBuilder.addQueryParameter("v", "1.0");
urlBuilder.addQueryParameter("user", "vogella");
String url = urlBuilder.build().toString();
Request request = new Request.Builder()
.url(url)
.build();
And after that you need to send your request (asynchronously) with the help of the OkHttpClient like this
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} else {
// do something wih the result
}
}
(Code was taken from Vogella)

How to get events in PAMI

I successfully insttalled PAMI in my server where asterisk is setup. And i wrote a new php file which
class A implements IEventListener
{
public function handle(EventMessage $event)
{
print_r("Inside");
}
}
$pamiClient = new PamiClient($pamiClientOptions);
$pamiClient->registerEventListener(new A());
$pamiClient->open();
$running = true;
while($running) {
$pamiClient->process();
usleep(1000);
}
$pamiClient->close();
But when i generate a call it doesnot catch the event. How can i know it is connected with asterisk, and how can i test this? Iam justng running this php file .
How i can know it connected to asterisk:
tcpdump -vv dst port 5038
how can i test this
Use debugger.

Messages not getting sent via ZMQ

Currently, i am trying a simple code of sending/receiving messages using ZMQ. The code is as below
/* Create new queue object, there needs to be a server at the other end */
$queue = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ);
$queue->connect("tcp://127.0.0.1:5555");
/* Assign socket 1 to the queue, send and receive */
$retries = 5;
$sending = true;
/* Start a loop */
do {
try {
/* Try to send / receive */
if ($sending) {
echo "Sending message\n";
$queue->send("This is a message", ZMQ::MODE_NOBLOCK);
$sending = false;
} else {
echo "Got response: " . $queue->recv(ZMQ::MODE_NOBLOCK) . "\n";
echo 'Complete';
break;
}
} catch (ZMQSocketException $e) {
/* EAGAIN means that the operation would have blocked, retry */
if ($e->getCode() === ZMQ::ERR_EAGAIN) {
echo " - Got EAGAIN, retrying ($retries)\n";
} else {
die(" - Error: " . $e->getMessage());
}
}
/* Sleep a bit between operations */
usleep(5);
} while (--$retries);
When i run this script in console, my output is
Sending message
Got response:
Complete
I believe that though there are no errors thrown, but still my message is not actually sent. I also ran netstat command but i didn't found any process listening on port 5555. Ideally there should be one(current). But no exception is thrown while making connection.
Is there something which i am missing?
When you say no process is listening on port 5555, it probably means that your server is not up and running. Your client will not throw any errors even if there is no server, it just sets up and waits for the server to come online (with your particular setup here, at least).
In this case, since you're using non-blocking mode, it'll send your message on the first pass through the loop (why are you sending the message in the loop at all?), but it won't actually send anything because the server isn't there. Then it'll attempt to receive on the second pass through the loop, but since the socket isn't ready to receive it looks like it'll just fail silently, without throwing an exception. Since no exception is thrown, it gets to your break statement, quits the loop, and you're done.
First things first, your send call should happen before the loop, it's something you want to do only once.
Then, when you recv, store the result in a variable and test for emptiness. Leave the try/catch code. The result should be something like this:
/* Create new queue object, there needs to be a server at the other end */
$queue = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ);
$queue->connect("tcp://127.0.0.1:5555");
/* Assign socket 1 to the queue, send and receive */
$retries = 5;
echo "Sending message\n";
$queue->send("This is a message", ZMQ::MODE_NOBLOCK);
/* Start a loop */
do {
try {
/* Try to receive */
$response = $queue->recv(ZMQ::MODE_NOBLOCK);
if (!empty($response)) {
echo "Got response: " . $response . "\n";
echo 'Complete';
break;
}
else {
echo "we probably haven't even sent the original request yet, retrying ($retries)\n";
}
}
catch (ZMQSocketException $e) {
/* EAGAIN means that the operation would have blocked, retry */
if ($e->getCode() === ZMQ::ERR_EAGAIN) {
echo " - Got EAGAIN, retrying ($retries)\n";
} else {
die(" - Error: " . $e->getMessage());
}
}
/* Sleep a bit between operations */
usleep(5);
} while (--$retries);
echo "END OF LINE";
... keep in mind this is a minor fix to the client code that makes it behave a little more rationally, I still believe your actual problem is that the server isn't running.
Please add the server code. You are showing the client code. Since the problem seems to be in the server, and you also state that the server is not visible with netstat, the problem is most probably there.

Android login activity using mysql database

Hi I am new to android and I am developing an app which has a login screen.
I have tried many tutorials but I am not sure how to connect the mysql database to my android app. In all the tutorials they have used php to connect the android app to the database.
What I want to know is that where exactly do I need to place the php file and where and how I need to create the php file.
I am creating the database using mysql workbench.
I am using eclipse 4.2 to write the java code.
Hi i am using the following code to check whether the user name i entered is correct or not along with the php code but the problem is that it always gives incorrect username.
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://192.168.3.27/abc/check.php", postParameters); //Enetr Your remote PHP,ASP, Servlet file link
String res=response.toString();
// res = res.trim();
res= res.replaceAll("\\s+","");
//error.setText(res);
error.setText(res);
if(res.equals("1")){
Intent myIntent = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(myIntent);
}
else
error.setText("Sorry!! Incorrect Username or Password");
This is my php code.
<?php
$un=$_POST['username'];
$pw=$_POST['password'];
//connect to the db
$user = ‘root’;
$pswd = ‘root’;
$db = ‘mylogin’;
$conn = mysql_connect(‘localhost’, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = “SELECT * FROM userpass WHERE login_id = ‘$un’ AND login_pass = ‘$pw’”;
$result = mysql_query($query) or die(“Unable to verify user because : ” . mysql_error());
//this is where the actual verification happens
if(mysql_num_rows($result) > 0)
echo 1; // for correct login response
else
echo 0; // for incorrect login response
?>
Here is the complete tutorial which you are searching for..
as like your normal html page, post the login values from the android device to the url and authenticate in php file as like the example
where exactly do i need to place the php file
You need to place PHP file in server. (You can use localhost i.e., your machine but for devices outside you need to keep it on a webserver which you need to purchase a domain and hosting services.)
where and how i need to create the php file.
You can create a PHP file in you machine itself. Its as simple as creating a text file but with an extension of .php. Using a wamp on windows (LAMP for linux)you can test it. It has a MySQL in it. LAMP and WAMP will have apache server by default.
Soon after you are finished with writing you php code and testing you can transfer the files through FTP into your webserver. Now to configure the MySQL database you can actually use a control panel at the webserver.
You need to use URL for android application to link the PHP files in turn these PHP files interact with MysQL. for a login lets think like you have created a php file as login.php. On your localhost you can refer it to as http://localhost/myapp/login.php If you need to get it on a webserver which you purchase then you URL will have http://www.yourwebsite.com/myapp/login.php. note that myapp is just a folder where you have uploaded your php files.
Now its just a way by which you can actually have a PHP and MySQL for you android application. I think that tutorials have taught you about using php and mysql connections. For Data exchange you need to know about XML or JSON I think tutorials followed had given you an introduction about it.
You even have a plugin for eclipse to work with php. Just get a help over internet on how to install it. This video might help you.
I'd like to brief raheel's answer, but in my own way. The important thing is that you need a server-client communication to access your my sql. For that you need to create a server which responds to requests from your android app. Your request shall be as follows
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://example.com/script.php?var1=androidprogramming");
try {
HttpResponse response = httpclient.execute(httpget);
if(response != null) {
String line = "";
InputStream inputstream = response.getEntity().getContent();
line = convertStreamToString(inputstream);
Toast.makeText(this, line, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Unable to complete your request", Toast.LENGTH_LONG).show();
}
} catch (ClientProtocolException e) {
Toast.makeText(this, "Caught ClientProtocolException", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, "Caught IOException", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Caught Exception", Toast.LENGTH_SHORT).show();
}
the consuming of output will be :
private String convertStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
Toast.makeText(this, "Stream Exception", Toast.LENGTH_SHORT).show();
}
return total.toString();
}
Then the server side can be like:
$connection = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die('Unable to connect');
$db = mysql_selectdb(DB_NAME,$connection) or die('Database not found');
if(isset($_GET['var'])) :
$query = "SELECT [a few parameters] FROM [some table] WHERE [some conditions]";
$resultset = mysql_query($query);
$row = mysql_fetch_array($resultset)
echo $row['[column name]'];
else:
echo "No get Request Received";
endif;
These are just snippets from which you can build on
For this purpose you should create a php application and host it on a server.
then using php create functions(or links available online) which will be hit by android application and they(functions) will output the data as json_encoded which is required by android. You can easily use this way to setup your application.
I usually use Codeigniter framework and it works like this.
myapp/
system/
application/
controllers/
mycontroller
mycontroller has some functions like this
function test(){
$username = $this->uri->segment(3);
$password = $this->uri->segment(4);
// other stuff like fetch data from db table in the variable $data
header('Content-Type: application/json');
echo json_encode($data);
}
And android needs this
http://testdomain/myapp/index.php/mycontroller/test/username/password
EDITS :
if you are usig plain php you can do it like this
Create a folder on your server.
create a file test.php create a connection file connection.php
include 2nd file in the first.
create a function in test.php named
include('connection.php');
function index($username,$password)
{
//query database table
//if result is success full
// $data = array('message'=>'login success');
//else
// $data = array('message'=>'login failed');
//
//header('Content-Type: application/json');
//echo json_encode($data);
}
from the address bar you can access it like this
http://tomcatserver/test.php/index/testuser/testpassword
You should do some research how php works

Categories