How can i run socket server in PHP? -
how can run socket server each www client?
i have simple socket_server:
<?php // set ip , 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 port $result = socket_bind($socket, $host, $port) or die(socket_strerror(socket_last_error($socket))); // start listening connections $result = socket_listen($socket, 3); // accept incoming connections // spawn socket 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 input string $input = trim($input); echo "client message : ".$input."<br />"; // reverse client input , send //$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 try run server in way:
<?php //include server.php script start server include_once('server.php'); include('socket.php'); $message = "hello server"; echo "message server :".$message; // create socket $socket = socket_create(af_inet, sock_stream, 0) or die("could not create socket\n"); // connect server $result = socket_connect($socket, $host, $port) or die("could not connect server\n"); // send string server socket_write($socket, $message, strlen($message)) or die("could not send data server\n"); // server response $result = socket_read ($socket, 1024) or die("could not read server response\n"); echo "reply server :".$result; // close socket socket_close($socket); ?>
i message:
only 1 usage of each socket address (protocol/network address/port) permitted.
i not have other communications on port. checked netstat.
Comments
Post a Comment