user2840866
user2840866

Reputation: 21

Php socket and while

I'm learning and trying to understand socket in php but I have a little problem with while loop.

This is my basic code :

Client Side

<?php
     set_time_limit(0);

     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

     $res = socket_connect($socket, '127.0.0.1', 2000);

     $input = "Client to Server Message";

     socket_write($socket, $input, strlen($input));
     $res = socket_read($socket, 1024);

     echo $res;

     socket_close($socket);
?>

And the server side

<?php
     set_time_limit(0);

     $address = "127.0.0.1";
     $port = 2000;

     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

     socket_bind($socket, $address, $port) or die("Can't bind the socket");

     socket_listen($socket);

     echo "Server waiting connexion...";

     $client = socket_accept($socket);

     $input = socket_read($client, 1024);

     echo "\nInput : ".$input;

     $output = 'Server to Client Message';

     socket_write($client, $output);

     socket_close($client);
     socket_close($socket);

     echo "\nServer closed";
 ?>

It works, but if I want to add a while loop on server side for handle multiple messages from the client side, my browser do an infinte loop and I can't get the message back from the server.

How I must to do in order to get this works ?

Can someone can explain me the basic way to do a chat-like using socket with PHP only (I can do this with socket.io and NodeJs) or send me to a good tutorial on the web ?

Upvotes: 2

Views: 1880

Answers (1)

mjb4
mjb4

Reputation: 987

I think you're a bit on the wrong path.

You wrote two little php scripts where the server side is not just a script running on a webserver but it's a server already. While your client side is exactly like a browser (just a bit basic). So straight to the point you wrote a chat application and a chat server but not a website.

Meaning you should run both scripts as a console script. On Linux you've got the "php " command. On Windows read this http://php.net/manual/de/install.windows.commandline.php

If you just want a simple chat use this:

<!-- html stuff -->
<pre>
<?php
//chat.php

// Safe message on server using file
if(isset($_GET['msg'])){
    // be carefull it's not clever to let the world write
    // to your server even if it's a textfile
    $f = fopen("db.txt","a+");
    fputs($f, $_GET['msg']);
    fclose($f);
}

// print all messages
readfile("db.txt");

?>
</pre>
<form>
 <textarea name="msg"></textarea>
 <input type="submit"/>
</form>

For more chat like feeling, meaning no reload of page required you need Javascript and AJAX requests. Look here http://www.w3schools.com/php/php_ajax_php.asp

The Problem is all good tutorials for chat's I found and used myself are normally also using a mysql database.

Upvotes: 1

Related Questions