I have a problem with android client receiving data from php server. Android can successfully writes data to php server and server accepts that data and then send back response to that client but android is not accepting. it does not move forward from Socket s = ss.accept()
Here is my android code to recieve data
public void run() {
Boolean end = false;
ServerSocket ss = serverSocket;
/*try {
ss = new ServerSocket(54546);
} catch (IOException e1) {
//TODO Auto-generated catch block
e1.printStackTrace();
}*/
while(!end){
//Server is waiting for client here, if needed
try {
Log.i("before accept", "yes");
Socket s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
//PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
String st = input.readLine();
Log.d("Tcp Example", "From client: "+st);
//output.println("Good bye and thanks for all the fish :)");
}catch (IOException e) {
e.printStackTrace();
}
}
}
Here is my php code
$host = "127.0.0.1";
$port = 54546;
set_time_limit(0);
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
//$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n");
/*if (!socket_connect($socket, $host, $port)) {
die('failed'.socket_strerror(socket_last_error($socket)));
}*/
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
echo socket_strerror(socket_last_error($socket));
exit;
}
$result = socket_bind($socket, $host, $port) or die("Could not create socket\n");
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
echo "\nbefore socket accept while loop\n";
$aaa = fopen("tesst.txt", "w");
while(true)
{
echo "\nbefore socket accept\n";
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
echo "\nThe server is ready\n";
$input = socket_read($spawn, 1024) or die("Could not read input\n");
echo "Input recieved from $spawn : ".$input;
fwrite($aaa, $input);
$output = $input."\n";
$sent = socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
echo "Output sent ".$sent;
socket_close($spawn);
}
fclose($aaa);
socket_close($socket);
echo "\nTerminating\n";
ss.accept() is not accepting connection from server.
We don't have to do ss.accept() for the client as well. The client should establish the connection using the connect() and the server should do accept(). Once the connection is established, the server should use the file descriptor returned from the accept() to send and receive data to/from the client. On the other side, the client does not need to do any accept, it should simply call recv() to retrieve received data.
Thus, if the Android code is the client, then it should do a connect() call to the PHP server -- the connect() call would take the IP address and the port number (54546). With a successful connect() call, the accept() on the PHP would return.
Related
My problem is when I try to connect the Android application with Java socket identified by an IP and a port 4444 with a PHP service, identified by the same port, and keep this connection open to accept multiple connections via the Android app.
So with a second Android device if we connect to PHP we will have the same communication channel as the one device and we cannot identify which device is connected via PHP.
Is there a possibility to differentiate these two connections via the PHP file or instantiate two different PHP service for the two devices.
The Android code:
public String connect() {
Socket socket = null;
try {
socket = new Socket();
// This limits the time allowed to establish a connection in the case
// that the connection is refused or server doesn't exist.
socket.connect(new InetSocketAddress(dstAddress, dstPort), context.getResources().getInteger(R.integer.time_out));
// This stops the request from dragging on after connection succeeds.
socket.setSoTimeout(context.getResources().getInteger(R.integer.time_out));
// socket = new Socket();
// socket.connect(new InetSocketAddress(dstAddress, dstPort), 2000);
if (!socket.isConnected())
throw new SocketException("Could not connect to Socket");
DataInputStream DIStream = new DataInputStream(socket.getInputStream());
DataOutputStream DOStream = new DataOutputStream(socket.getOutputStream());
DOStream.write(numCmd.getBytes(), 0, numCmd.getBytes().length);
DOStream.flush();
response = DIStream.readLine();
DOStream.close();
DIStream.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "{\"Error_no\":5000}";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "{\"Error_no\":5000}";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "{\"Error_no\":5000}";
} finally {
if (socket != null) {
try {
socket.close();
if(response == null){
response = "{\"Error_no\":5000}";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "{\"Error_no\":5000}";
}
}
}
// Log.i("resp",response);
return response;
}
The PHP code:
<?php
echo "service php started \n";
$version = '2.2.0';
$address = '10.164.2.1';
$port = 4444;
$timeout= 2;
$cmd = explode("*", str_replace(array("/"), "*",
str_replace(" ","",shell_exec("netstat -tulpn | grep :".$port))));
echo "pid ".$cmd[1];
$cmd[1] = substr_replace($cmd[1], '', 0, 6);
echo "pid ".$cmd[1];
exec("kill -9 $cmd[1]");
sleep(1);
$socketPath = 'unix:///home/root/sockets/local_iapp_socket';
// Create WebSocket.
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
if(socket_bind($server, $address, $port)){
echo "Connected with tcp socket \n";
}else{
echo "connection with tc socket error \n";
}
socket_listen($server);
echo "server is listning \n";
$socket_fd = connect_socket_local();
echo "connected to unix socket \n";
while ($client = socket_accept($server)) {
$num_cmd = socket_read($client, 5000);
echo "Client Message : ".$num_cmd ."\n";
if($socket_fd != false){
$id=24;
$len= strlen($num_cmd);
$fwrite1 = fwrite($socket_fd, pack("L", $len),4);
if($fwrite1 === false){
$content = '{"Error_no":5000}';
echo "fwrite1 a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
exit;
}
$fwrite2 = fwrite($socket_fd,pack("L", $id),4);
if($fwrite2 === false){
$content = '{"Error_no":5000}';
echo "fwrite2 a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
exit;
}
$fwrite3 = fwrite($socket_fd,$num_cmd,strlen($num_cmd));
if($fwrite3 === false){
$content = '{"Error_no":5000}';
echo "fwrite3 a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
exit;
}
$content = fread($socket_fd, 5000) ;
if( $content == null){
echo "impossible d'atteindre la socket locale" . socket_strerror(socket_last_error()) . "\n";
$content = '{"Error_no":5000}';
}
}else{
$content = '{"Error_no":5000}';
echo "problème de connexion" . socket_strerror(socket_last_error()) . "\n";
}
$json_resp = $content;
echo "json_resp" . $json_resp."\n\r";
socket_write($client, $json_resp,strlen($json_resp));
socket_close($client);
}
socket_close($server);
function connect_socket_local()
{
global $socketPath , $timeout;
if (($socket_fd= stream_socket_client($socketPath , $errorno, $errorstr, $timeout)) === false) {
echo "stream_socket_client a échoué : raison : " . socket_strerror(socket_last_error()) . "\n";
}
return $socket_fd;
}
?>
You can run a separate server process for each client. Each server process needs to have an unique IP address or TCP port. Each client needs to be configured to connect to the correct server address and port. This is difficult to manage and doesn't scale.
At the server side, you can get the peer address, that is the IP address and port of the client. In PHP, you can use socket_getpeername() for this. However, depending on the network setup, this might not be the IP address of the client itself. It can be the IP address of an intermediate gateway or other network device. Also, the client IP address might be dynamic.
The best solution is to send some identification from the client to the server when the clients connects to the server. This can be a name or some other unique identification. You have to change the protocol between the client and server to support this. The client needs to know when and how to send the identification. The server needs to know when and how to receive the identification.
How to send a php array to a socket server?
I have a webservice and i want to send a php array to a socket webservices.
How i can do it?
I have tried this:
$host = "170.51.249.101";
$port = 8080;
// No Timeout
set_time_limit(0);
// Create a Data to send
$data = "";
$data .= "ID_PRESTADOR: ".$service_id."\n";
$data .= "ID_TERMINAL: ".$atm_id."\n";
$data .= "NRO_TRANSACCION: 123456\n";
// Create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// Connect to the server
$result = socket_connect($socket, $host, $port) or die("Could not connect toserver\n");
// Write to server socket
socket_write($socket, $data, strlen($data)) or die("Could not send data to server\n");
// Read the response from the server
$result = socket_read ($socket, 1024) or die("Could not read server response\n");
echo "Reply From Server :".$result;
// Close the socket
socket_close($socket);
die;
I have an own file that receives for post a request ajax, But the request never comes.
In a view:
<script type="text/javascript">
$(document).ready(function(){
$("#bloquear").click(function(e){
$.post("proyectodam/app/Lib/ServerSocket.php", {op: 1});
});
});
</script>
The php I have it in a directory that I have created,His namespaces:
namespace proyectodam\Lib;
file PHP:
<?php
namespace proyectodam\Lib;
try{
set_time_limit(0);
$address = '127.0.0.1';
$port = 5555;
// Create a TCP Stream socket
$sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); // 0 for SQL_TCP
// Bind the socket to an address/port
socket_bind($sock, $address, $port) or die('Could not bind to address'); //0 for localhost
// Start listening for connections
socket_listen($sock);
//loop and listen
while(true){
/* Accept incoming requests and handle them as child processes */
$client = socket_accept($sock);
//$_SESSION[socket_getpeername($client, AF_INET, 5555)] = socket_getpeername($client, AF_INET, 5555);
// Read the input from the client – 1024000 bytes
//$input = socket_read($client, 1024000);
// from here you need to do your database stuff
// and handle the response
// Display output back to client
if(isset($_POST["op"])){
$message = 1;
socket_write($client, $message, strlen($message));
}
socket_close($client);
}
// Close the master sockets
socket_close($sock);
}catch(Exception $e){
echo 'Excepción capturada: ', $e->getMessage(), "\n";
}
Client java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class ClienteSocket{
public static void main(String args[]){
try {
Socket client = new Socket("127.0.0.1", 5555);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
OutputStreamWriter wr = new OutputStreamWriter(client.getOutputStream());
String op;
while((op = in.readLine()) != null){
System.out.println(op);
}
}catch (IOException e){
System.out.println("error");
e.printStackTrace();
}
}
}
That fails?
If you are making a post request to proyectodam/app/Lib/ServerSocket.php You need to make sure that you have a file in /public/proyectodam/app/Lib/ServerSocket.php
What I would suggest doing however is making an api endpoint such as:
Route::post('socket', function() {
return new ClientSocket();
}
And then have your client socket library class be:
<?php
namespace proyectodam\Lib;
class ClienteSocket {
public function __construct()
{
try{
set_time_limit(0);
$address = '127.0.0.1';
$port = 5555;
// Create a TCP Stream socket
$sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); // 0 for SQL_TCP
// Bind the socket to an address/port
socket_bind($sock, $address, $port) or die('Could not bind to address'); //0 for localhost
// Start listening for connections
socket_listen($sock);
//loop and listen
while(true){
/* Accept incoming requests and handle them as child processes */
$client = socket_accept($sock);
//$_SESSION[socket_getpeername($client, AF_INET, 5555)] = socket_getpeername($client, AF_INET, 5555);
// Read the input from the client – 1024000 bytes
//$input = socket_read($client, 1024000);
// from here you need to do your database stuff
// and handle the response
// Display output back to client
if(isset($_POST["op"])){
$message = 1;
socket_write($client, $message, strlen($message));
}
socket_close($client);
}
// Close the master sockets
socket_close($sock);
} catch(Exception $e){
echo 'Excepción capturada: ', $e->getMessage(), "\n";
}
}
}
I manage to send data for ajax (jquery) to the server TCP who is running for line of commands, but apparently the serveris unable to handle them.
From this JS/HTML I try to send data to the server.
<script type="text/javascript">
$(document).ready(function(){
$("#bloquear").click(function(){
$.post("http://localhost/proyectodam/app/Lib/ServerSocket.php", {op: 1});
});
});
</script>
Server in PHP.
<?php
namespace proyectodam\Lib;
try{
set_time_limit(0);
$address = '127.0.0.1';
$port = 5555;
// Create a TCP Stream socket
$sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); // 0 for SQL_TCP
// Bind the socket to an address/port
socket_bind($sock, $address, $port) or die('Could not bind to address'); //0 for localhost
// Start listening for connections
socket_listen($sock);
//loop and listen
while(true){
/* Accept incoming requests and handle them as child processes */
$client = socket_accept($sock);
//$_SESSION[socket_getpeername($client, AF_INET, 5555)] = socket_getpeername($client, AF_INET, 5555);
// Read the input from the client – 1024000 bytes
//$input = socket_read($client, 1024000);
// from here you need to do your database stuff
// and handle the response
// Display output back to client
if(isset($_POST["op"]) && $_POST["op"] == 1){
$message = $_POST["op"];
socket_write($client, $message, strlen($message));
//echo json_encode("si");
}
socket_close($client);
}
// Close the master sockets
socket_close($sock);
}catch(Exception $e){
echo 'Excepción capturada: ', $e->getMessage(), "\n";
}
Client Java.
public class ClienteSocket{
public static void main(String args[]){
try {
Socket client = new Socket("127.0.0.1", 5555);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
OutputStreamWriter wr = new OutputStreamWriter(client.getOutputStream());
String op;
while((op = in.readLine()) != null){
System.out.println(op);
}
}catch (IOException e){
System.out.println("error");
e.printStackTrace();
}
}
}
How the server intercept the data that come for ajax and once obtained to send to the client Java?
How can i run socket server for each www client?
I have simple socket_server:
<?php
// set ip and port
include('socket.php');
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "-1";
exit;
}
// bind socket to port
$result = socket_bind($socket, $host, $port) or die(socket_strerror(socket_last_error($socket)));
// start listening for connections
$result = socket_listen($socket, 3);
// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
echo "Server: Ready.";
while(1) {
// read client input
$input = socket_read($spawn, 1024) or die("Could not read input\n");
// clean up input string
$input = trim($input);
echo "Client Message : ".$input."<br />";
// reverse client input and send back
//$output = strrev($input) ."<br />";
$output = "output message";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
}
// close sockets
socket_close($spawn);
socket_close($socket);
?>
Now when i try run server in this way:
<?php
//include the server.php script to start the server
include_once('server.php');
include('socket.php');
$message = "Hello Server";
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);
?>
I get the message:
Only one usage of each socket address (protocol/network address/port) is normally permitted.
I do not have any other communications on this port. I checked the netstat.