Home >Backend Development >PHP Tutorial >PHP simply implements Socket communication between client and server
This article will introduce you to the process of PHP simply realizing Socket communication between the client and the server.
The socket method used in this article.
socket server implementation codeserver.php
<?php /** * Created by PhpStorm. * User: jmsite.cn * Date: 2019/2/20 * Time: 11:59 */ set_time_limit(0); $host = '127.0.0.1'; $port = 8081; $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP) or die("socket_create() 失败:".socket_strerror(socket_last_error())."\n"); $ret = socket_bind($socket,$host,$port) or die("socket_bind() 失败:".socket_strerror(socket_last_error())."\n"); $ret = socket_listen($socket,10) or die("socket_listen() 失败:".socket_strerror(socket_last_error())."\n"); while (true){ $connection = socket_accept($socket) or die("socket_accept() 失败:".socket_strerror(socket_last_error())."\n"); while (true){ socket_getpeername($connection, $addr, $port); $data = socket_read($connection, 4096); if (!$data){ break; } $msg = date("Y-m-d H:i:s")." {$addr} {$port} 已收到信息(".$data.")"; echo $msg."\n"; socket_write($connection, $msg, strlen($msg)); } }
socket client implementation codeclient.php
<?php /** * Created by PhpStorm. * User: jmsite.cn * Date: 2019/2/20 * Time: 12:22 */ $host = '127.0.0.1'; $port = 8081; $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP) or die("socket_create() 失败:".socket_strerror(socket_last_error())."\n"); $ret = socket_connect($socket, $host, $port) or die("socket_connect() 失败:".socket_strerror(socket_last_error())."\n"); $msg = "测试发送信息,pid:".getmypid(); socket_write($socket, $msg, strlen($msg)); $data = socket_read($socket, 4096); echo "server回复:".$data."\n"; socket_close($socket);
Test socket communication
Execute server code, block and wait for client connection
php server.php
Execute client code multiple times
php client.php server回复:2019-02-20 10:14:33 127.0.0.1 64238 已收到信息(测试发送信息,pid:1532) php client.php server回复:2019-02-20 10:14:34 127.0.0.1 64242 已收到信息(测试发送信息,pid:11620) php client.php server回复:2019-02-20 10:14:35 127.0.0.1 64243 已收到信息(测试发送信息,pid:3676) php client.php server回复:2019-02-20 10:14:36 127.0.0.1 64246 已收到信息(测试发送信息,pid:19740) php client.php server回复:2019-02-20 10:14:37 127.0.0.1 64249 已收到信息(测试发送信息,pid:23180) ......
server.php output
php server.php 2019-02-20 10:14:33 127.0.0.1 64238 已收到信息(测试发送信息,pid:1532) 2019-02-20 10:14:34 127.0.0.1 64242 已收到信息(测试发送信息,pid:11620) 2019-02-20 10:14:35 127.0.0.1 64243 已收到信息(测试发送信息,pid:3676) 2019-02-20 10:14:36 127.0.0.1 64246 已收到信息(测试发送信息,pid:19740) 2019-02-20 10:14:37 127.0.0.1 64249 已收到信息(测试发送信息,pid:23180) ......
This is the process of PHP simply realizing Socket communication between the client and the server.
The above is the detailed content of PHP simply implements Socket communication between client and server. For more information, please follow other related articles on the PHP Chinese website!