简单地拿php的socket写了个小daemo, 代码如下:
server端:
<?php
$address = "127.0.0.1";
$port = 20461;
//创建socket资源
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("socket_create() 失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
//阻塞模式
socket_set_block($sock) or die("socket_set_block() 失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
//绑定到socket端口
$result = socket_bind($sock, $address, $port) or die("socket_bind() 失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
//监听端口
$result = socket_listen($sock) or die("socket_listen() 失败的原因是:" . socket_strerror(socket_last_error()) . "/n");
echo "OKnBinding the socket on $address:$port ... ";
echo "OKnNow ready to accept connections.nListening on the socket ... n";
do {
$msgsock = socket_accept($sock) or die("socket_accept() failed: reason: " . socket_strerror(socket_last_error()) . "/n");
echo "Read client data \n";
$buf = socket_read($msgsock, 8192, PHP_NORMAL_READ);
echo "Received msg: $buf \n";
//数据传送 向客户端写入返回结果
$msg = "welcome" . PHP_EOL;
socket_write($msgsock, $msg, strlen($msg)) or die("socket_write() failed: reason: " . socket_strerror(socket_last_error()) ."/n");
socket_close($msgsock);
} while (true);
socket_close($sock);
client端:
<?php
global $argv;
$host = "127.0.0.1";
$port = 20461;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)or die("Could not create socketn"); // 创建一个Socket
$connection = socket_connect($socket, $host, $port) or die("Could not connet servern"); // 连接
socket_write($socket, $argv[1] . PHP_EOL) or die("Write failedn");
//$buff = socket_read($socket, 1024, PHP_NORMAL_READ);
while ($buff = socket_read($socket, 1024, PHP_NORMAL_READ)) {
echo("Response was:" . $buff . PHP_EOL);
}
socket_close($socket);
我把服务端启动之后,客户端发送数据会报错:
但是把客户端的socket_read改成PHP_BINARY_READ就可以了;
守候你守候我
缥缈止盈
慕慕森