I want to implement chat functions using websocket in android with php.
I need PHP code for the same.
The scenario is as follows.
The Android developer will send a message from the android device to the php application, and not with php, the message will be sent to another Android phone for which it is intended.
After that I also need to save all the chats in the database.
I have no idea how to do this.
Please help and provide a code for this.
The code I wrote is as follows.
$address = "0.0.0.0";
$port = 5000;
$max_clients = 10;
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
if( !socket_bind($sock, $address , 5000) )
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not bind socket : [$errorcode] $errormsg \n");
}
echo "Socket bind OK \n";
if(!socket_listen ($sock , 10))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
echo "Socket listen OK \n";
echo "Waiting for incoming connections... \n";
$client_socks = array();
$read = array();
while (true)
{
$read = array();
$read[0] = $sock;
for ($i = 0; $i < $max_clients; $i++)
{
if($client_socks[$i] != null)
{
$read[$i+1] = $client_socks[$i];
}
}
if(socket_select($read , $write , $except , null) === false)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not listen on socket : [$errorcode] $errormsg \n");
}
if (in_array($sock, $read))
{
for ($i = 0; $i < $max_clients; $i++)
{
if ($client_socks[$i] == null)
{
$client_socks[$i] = socket_accept($sock);
if(socket_getpeername($client_socks[$i], $address, $port))
{
echo "Client $address : $port is now connected to us. \n";
}
$message = "Welcome to php socket server version 1.0 \n";
$message .= "Enter a message and press enter, and i shall reply back \n";
socket_write($client_socks[$i] , $message);
break;
}
}
}
for ($i = 0; $i < $max_clients; $i++)
{
if (in_array($client_socks[$i] , $read))
{
$input = socket_read($client_socks[$i] , 1024);
if ($input == null)
{
unset($client_socks[$i]);
socket_close($client_socks[$i]);
}
$n = trim($input);
$output = "OK ... $input";
socket_write($client_socks[$i] , $output);
}
}
}
source
share