PHP实现Socket服务器的代码_php教程-查字典教程网
PHP实现Socket服务器的代码
PHP实现Socket服务器的代码
发布时间:2016-12-29 来源:查字典编辑
摘要:然后打开CMD,输入:telnet192.40.7.9310000,自己体验去吧!注,要把:php_sockets.dll打开

<?php

ob_implicit_flush();

set_time_limit(0);

$address="192.40.7.93";//换成你自己的地址

$port=10000;

if(($socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP))==false)

echo"错误(socket_create):".socket_strerror(socket_last_error())."<br/>";

if(socket_bind($socket,$address,$port)==false)

echo"错误(socket_bind):".socket_strerror(socket_last_error())."<br/>";

if(socket_listen($socket)==false)

echo"错误(socket_listen):".socket_strerror(socket_last_error())."<br/>";

/*

Afterthesocketsockethasbeencreatedusingsocket_create()andboundtoanamewithsocket_bind(),

itmaybetoldtolistenforincomingconnectionsonsocket.

*/

while(true){

if(($msgSocket=socket_accept($socket))==false){

echo"错误(socket_accept):".socket_strerror(socket_last_error())."<br/>";

break;

}

/*

thisfunctionwillacceptincomingconnectionsonthatsocket.

Onceasuccessfulconnectionismade,anewsocketresourceisreturned,whichmaybeusedforcommunication.

Iftherearemultipleconnectionsqueuedonthesocket,thefirstwillbeused.

Iftherearenopendingconnections,socket_accept()willblockuntilaconnectionbecomespresent.

Ifsockethasbeenmadenon-blockingusingsocket_set_blocking()orsocket_set_nonblock(),FALSEwillbereturned.

*/

$msg="Welcome!<br/>";

//socket_write($msg,$msg,strlen($msg));

$command="";

while(true){

if(($buf=socket_read($msgSocket,2048,PHP_BINARY_READ))==false){

echo"错误(socket_read):".socket_strerror(socket_last_error())."<br/>";

break2;

}

/*

Thefunctionsocket_read()readsfromthesocketresourcesocketcreatedbythesocket_create()orsocket_accept()functions.

Themaximumnumberofbytesreadisspecifiedbythelengthparameter.

Otherwiseyoucanuser,n,ortoendreading(dependingonthetypeparameter,seebelow).

*/

/*

if(!$buf=trim($buf))

continue;//????

if($buf=="quit")

break;

if($buf=="shutdown"){

socket_close($msgSocket);

break2;

}

$tallBack="Yousay:$bufn";

socket_write($msgSocket,$tallBack,strlen($tallBack));

*/

if(ord($buf)!=13)

$command.=$buf;

else{

$command1="YouSay:$commandrn";

socket_write($msgSocket,$command1,strlen($command1));

echo"Usertyped:".$command."<br/>";

$command="";

}

}

socket_close($msgSocket);

}

socket_close($socket);

?>

然后打开CMD,输入:telnet192.40.7.9310000,自己体验去吧!

注,要把:php_sockets.dll打开

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新php教程学习
    热门php教程学习
    编程开发子分类