Home > php教程 > PHP源码 > body text

php socket客户端和服务端互相通讯实例

WBOY
Release: 2016-06-08 17:22:09
Original
1069 people have browsed it

php socket是一个什么东西我就不介绍了,下面来给大家整理了一些关于php socket的实现的客户端与服务端互相通讯的例子。

<script>ec(2);</script>

服务端

 代码如下 复制代码

    set_time_limit(0);
    $host="localhost";
    $port=1001;
     
    //创建一个连接
    $socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP)or die("cannot create socketn");
    //绑定socket到端口
    $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");
    //接受连接,另一个socket来处理通信
    $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连接
    socket_close($msgsock);
    socket_close($socket);
 
?>

客户端

 代码如下 复制代码

    set_time_limit(0);
    $host="localhost";
    $port=1001;
     
    //创建一个socket
    $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);
?>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template