Server
1
Php2Set_time_limit(0);34$ip= ' 127.0.0.1 ';5$port= 8888;67//1. Create8if( ($sock= Socket_create (Af_inet, sock_stream, sol_tcp) = =FALSE ){9Echo' Create fail: '.Socket_strerror (Socket_last_error ());Ten} One A//2. Binding -if(Socket_bind ($sock,$ip,$port) ==FALSE ) { -Echo' Bind fail: '.Socket_strerror (Socket_last_error ()); the} - -//3. Monitoring -if(Socket_listen ($sock, 4) = =FALSE ){ +Echo' Listen fail: '.Socket_strerror (Socket_last_error ()); -} + A$count= 0; at - Do{ -//4. Blocking, waiting for client requests -if( ($msgsock= Socket_accept ($sock)) ==FALSE ) { - -Echo' Accept fail: '.Socket_strerror (Socket_last_error ()); in - Break; to}Else { + -//5. Writing information to the client the$msg= ' Server Send successfully! '; *Socket_write ($msgsock,$msg,strlen($msg)); $Panax Notoginseng -//5. Read Client information theEcho'-----test successfully!------'; +$buf= Socket_read ($msgsock, 8192); A the +$talkback= ' Receive client: '.$buf; -Echo$talkback; $ $ -if($count>= 5) { - Break; the } - }Wuyi the//6. Close the socket -Socket_close ($msgsock); Wu -} while(true); About $//6. Close the socket -Socket_close ($sock);
Client
Phperror_reporting(E_all);Set_time_limit(0);$ip= ' 127.0.0.1 ';$port= 8888;//1. Create$socket= Socket_create (Af_inet, Sock_stream,sol_tcp);if($socket==FALSE ) { Echo' Create fail: '.Socket_strerror (Socket_last_error ());} Else { Echo' OK ';}//2. LinksEcho' We'll try to connect '.$ip.':' .$port. ' \ r \ n----';$result= Socket_connect ($socket,$ip,$port);if($result==FALSE) { }$in= ' HO ';$in. = ' First Blood--------';$out= '';//3. Writing to the serverif(!socket_write ($socket,$in,strlen($in)) ) { Echo' Write fail: '.Socket_strerror (Socket_last_error ());} Else { Echo'-----Send to server succefully! \ r \ n----'; Echo' The content is '.$in;}//3. Read from the server while($out= Socket_read ($socket, 8129) ) { Echo'-----receive from server succefully!\r\n------'; Echo' The contents is '.$out;}//4. CloseEcho'----close socket ... '; Socket_close ($socket);Echo' Closed ok. ';
The above describes the Phpsocket simple PHP socket instance, including the phpsocket aspects of the content, I hope that the PHP tutorial interested in a friend helpful.