php socket客户端和服务端互相通讯实例
php socket是一个什么东西我就不介绍了,下面来给大家整理了一些关于php socket的实现的客户端与服务端互相通讯的例子.
服务端代码如下:
- <?php
- set_time_limit(0);
- $host="localhost";
- $port=1001;
-
-
- $socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP)or die("cannot create socketn");
-
- $result=socket_bind($socket,$host,$port) or die("cannot bind port to socketn");
-
- $result=socket_listen($socket,4) or die("could not set up socket listenn");
-
- $msgsock=socket_accept($socket) or die("cannot accept incoming connectionn");
- if($msgsock){
- echo date("Y-m-d H:i:s D a");
- }
-
- $input=socket_read($msgsock,1024) or die("cannot read inputn");
- $input=trim($input);
- $output=strrev($input)."顺序反过来了吧n";
-
- socket_write($msgsock,$output,strlen($output)) or die("cannot write");
-
- socket_close($msgsock);
- socket_close($socket);
- ?>
客户端代码如下:
- <?php
- set_time_limit(0);
- $host="localhost";
- $port=1001;
-
-
- $socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP)or die("cannot create socketn");
-
- $conn=socket_connect($socket,$host,$port) or die("cannot connect servern");
-
- if($conn){echo "client connect ok!";}
-
- socket_write($socket,"hello world!") or die("cannot write datan");
-
- $buffer=socket_read($socket,1024,PHP_NORMAL_READ);
-
- if($buffer){
- echo "response was:".$buffer."n";
- }
- socket_close($socket);
- ?>