PHP中socket通信

2017-01-13 10:55:47来源:csdn作者:q601115211人点击

第七城市

先写了个简单的例子,以后有机会再慢慢补充。 在CMD下启动服务端(php socketServer.php),然后启动客户端(php socketClient.php),输入文字就能发送了。

socketClent.php

$addr = "127.0.0.1";
$port = 8080;
fwrite(STDOUT,"Please input a argument:");
$message = trim(fgets(STDIN));echo "Message To server $message /n";$sock = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket/n");;$result = socket_connect($sock, $addr, $port) or die("Could not connect to server/n");socket_write($sock, $message, strlen($message)) or die("Could not send data to server/n");$result = socket_read ($sock, 1024) or die("Could not read server response/n");
echo "Reply From Server$result /n";socket_close($sock);

socketServer.php

<?php
set_time_limit(0);
$addr = "127.0.0.1";
$port = 8080;
$sock = socket_create(AF_INET, SOCK_STREAM, 0);if($sock < 0)
{
echo "failed to create socket: ".socket_strerror($sock)."/n";
exit();
}$ret = socket_bind($sock, $addr, $port);
$listen =socket_listen($sock, $port);
echo "listen $port .../n";while(true)
{
if(($newc = socket_accept($sock)) !== false)
{
$line = trim(socket_read($newc, 1024));
echo "Client msg: $line /n";fwrite(STDOUT,"Please input a argument:");
$message = trim(fgets(STDIN));socket_write($newc , $message);
echo "Message To Client $message /n";
}
}socket_close($sock);
第七城市

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台