- I have written a very simple socket server.
- It listens in post 63254.
- First i did a socket_create, socket_bind, socket_listen so here a connection is listening.
- Then in a loop i do the socket accpet. so here another listen.
- the read function reads untill i input exit.
- after that the resource id by socket_accept closes.
- and then the main connection closes.
when i checked this process in TCPview after closing all connections i can still see the system process showing TIME_WAIT for post 63254
if i again run the socket server program it is connecting and when one full process is over all the connection is closed and the program terminated and now i can see another TIME_WAIT for the same port. but still i could connect to the same port the third time.
in stackover question answer it is said that connection cannot be done for port which is in wait state.
I opened firefox browser it opened 4 connections. when i closed it all closed and the system process showed 4 time waits for 2 minutes. all time wait stays for 2 minutes and disappears.
so what i conclude is for every connection close the time wait is occurs and cannot be avoided.
i read many posts in stack overflow flow but still wasn't sure of it.
i run the following code in command line.
My server Code
<?
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
$str = '';
$buff = '';
$s = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if(!$s)die('Unable to create socket');
if(!socket_bind($s,'127.0.0.1',63254))
die("\nTrying to Bind: ".socket_strerror(socket_last_error()));
if(!socket_listen($s,1))
die(socket_strerror(socket_last_error()));
while(1)
{
$acc = socket_accept($s);
if(!$acc)die(socket_strerror(socket_last_error()));
// echo "\n".gettype($acc);
if(!$acc)die(socket_strerror(socket_last_error()));
while(1)
{
$str = socket_read($acc,512);
$buff.= $str;
echo $str;
// echo '::'.gettype($str);
if($str===false)die(socket_strerror(socket_last_error()));
if($str=="exit\r\n")break;
}
// if(!socket_shutdown($acc,2))echo socket_strerror(socket_last_error());
socket_close($acc);
if(preg_match('/exit/',$buff))break;
}
//echo "\nConnection closed by server\n";
//if(!socket_shutdown($s,2))echo socket_strerror(socket_last_error());
socket_close($s);
?>
The client code
<?
set_time_limit(0);
$f = fsockopen('127.0.0.1',63254,$a,$b,10);
if(!$f)die('cannot connect');
echo "\nConnected: \n";
do{
$buff = fgets(STDIN);
fwrite($f,$buff);
}while($buff!="exit\r\n");
fclose($f);
?>
need suggestions to improve a better client server if this is not sufficient. this code is just a child's play. just trying to understand the way communication works.