Jump to content

PHP SOCKET SERVER CANNOT SEND MESSAGE TO THE CLIENT


owned

Recommended Posts

Following socket server receives data from clients instantly as it should be. But server can send data to the client only when _client first makes a request_ to the server. How can server send data to the client instantly without needing client(s) to do requests every fraction of seconds to retrieve data in intensive apps ?? Help ???

 

If any client sends message to the server then some message can be distributed to other connected idle clients using that commented code. But how to make server send message without client's request?

 

Socket_accept() might be the reason?

 

E.g. how to make this following code to send messages to connected client(s) every second?

 

Code:

 

<?php 


$running=1;

$print_send = "echo (\"<font color='red'>{\$output}</font>\");
ob_flush();flush();";
$print_receive = "echo (\"<font color='green'>{\$input}</font>\");
ob_flush();flush();";

echo("
<html>
<head>

</head>
<body>
");

echo ("<h1>SERVER</h1><br><font color='green'>RUNNING...</font>");
ob_flush();flush();



// Set time limit to indefinite execution 
set_time_limit (0); 

// Set the ip and port we will listen on 
$address = '<ip>'; 
$port = 666;
$max_clients = 10;

// Array that will hold client information 
$clients = Array();
$sid_socket_list=array();

// Create a TCP Stream socket 
$sock = socket_create(AF_INET, SOCK_STREAM, 0); 
// Bind the socket to an address/port 
socket_bind($sock, $address, $port) or die('Could not bind to address'); 
// Start listening for connections 
socket_listen($sock); 

// Loop continuously 
while($running==1){

    // Setup clients listen socket for reading 
    $read[0]=$sock; 
    for($i = 0; $i < $max_clients; $i++){ 
        if($client[$i]['sock'] != null){
            $read[$i + 1] = $client[$i]['sock'];
	}
    } 
    // Set up a blocking call to socket_select() 
$ready = socket_select($read, $write = NULL, $except = NULL, $tv_sec = NULL);
    // if a new connection is being made add it to the client array
    if(in_array($sock, $read)){ 
        for($i=0;$i<$max_clients;$i++){
            if($client[$i]['sock'] == null){
                $client[$i]['sock'] = socket_accept($sock);
			socket_getpeername($sock, $ip);

			$output = "welcome";
			socket_write($client[$i]['sock'],$output.chr(0));
			eval($print_send);

                break;
            }elseif($i == $max_clients - 1){
                echo("too many clients");
		}

        } 
        if(--$ready <= 0){
            continue;
	}
    } // end if in_array 
     

    // If a client is trying to write - handle it now 
    for($i=0;$i<$max_clients;$i++){ // for each client


        if(in_array($client[$i]['sock'] , $read)){ 


            $input = socket_read($client[$i]['sock'] , 1024);
		eval($print_receive);


            if($input==null){
                // Zero length string meaning disconnected 
                unset($client[$i]); 
            }
            $input = trim($input);
            if($input == 'exit'){
                // requested disconnect
                socket_close($client[$i]['sock']); 
			unset($client[$i]);
            }elseif($input=='shutdown'){
                // shutdown server
                socket_close($client[$i]['sock']);
			unset($client[$i]);
			$running=0;
		}elseif($input){ 
                // strip white spaces and write back to user 
                //$output = ereg_replace("[ \t\n\r]","",$input).chr(0); 
                //socket_write($client[$i]['sock'],$output); 
			//eval($print_send);

			//$output = 'test';
                //socket_write($client[$i]['sock'],$output); 
			//eval($print_send);



/*












PROCESS CLIENT INPUT



Send message to all clients:

						$output='message';
						for($j=0;$j<$max_clients;$j++){ 
							if($client[$j]['sock']){
								socket_write($client[$j]['sock'], $output.chr(0));
								eval($print_send);
							} 
						}








*/


            } //end input

        }else{ 
            // Close the socket 
            //socket_close($client[$i]['sock']); 
            //unset($client[$i]); 
        }
    }//end for


} //end while

// Close the master sockets 
socket_close($sock); 
echo "<br><font color=red>SHUTDOWN</font>";

?>

Link to comment
Share on other sites

While asynchronous is meant to include both way of communication, the basic AJAX code will not allow for this, but there are a few frameworks that already do:

http://www.trapets.com/page.jsp?node=559

 

The more realistic solution is to just stick with polling the server on a variable rate that does not affect your hardware, and upgrade when things get out of hand. Here's some more info:

http://www.pushlets.com/doc/whitepaper-all.html

 

Good luck, I would like to someday do this myself. I'm sure in a few years AJAX 2.0 will be server-side initiated requests.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.