• socket数据通讯


    1、服务器监听

     1 error_reporting(E_ALL);
     2 //端口111
     3 $service_port = 1234;
     4 //本地
     5 $address = '192.168.0.103';
     6 //创建 TCP/IP socket
     7 $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     8 echo $socket;
     9 var_dump($socket);
    10 if ($socket < 0)
    11 {
    12     echo "socket创建失败原因: " . socket_strerror($socket) . "
    ";
    13 }
    14 else
    15 {
    16     echo "OK,HE HE.
    ";
    17 }
    18 $result = socket_connect($socket, $address, $service_port);
    19 if ($result)
    20 {
    21     echo "OK.
    ";
    22 }
    23 else
    24 {
    25     echo "SOCKET连接失败原因: ($result) " . socket_strerror($result) . "
    ";
    26 }
    27 
    28 //发送命令
    29 $in = "HEAD / HTTP/1.1
    ";
    30 $in .= "Connection: Close
    
    ";
    31 $out = '';
    32 echo "Send Command..........";
    33 $in = "sun
    ";
    34 socket_write($socket, $in, strlen($in));
    35 echo "OK.
    ";
    36 echo "Reading Backinformatin:
    
    ";
    37 while ($out = socket_read($socket, 2048)) {
    38     echo $out;
    39 }
    40 echo "Close socket........";
    41 socket_close($socket);

    2、客户端访问

     1 $attr = array("id"=>"admin","pw"=>"admin","mark"=>"1");
     2 $json = json_encode($attr);
     3 set_time_limit(0);
     4 //192.168.247.1
     5 $host = "192.168.0.103";
     6 $port = 12345;
     7 $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)or die("Could not create    socket
    "); // 创建一个Socket
     8 $user = "admin";
     9 $connection = socket_connect($socket, $host, $port) or die("Could not connet server
    ");    //  连接
    10 socket_write($socket, $json) or die("Write failed
    "); // 数据传送 向服务器发送消息
    11 while ($buff = @socket_read($socket, 1024, PHP_NORMAL_READ)) {
    12     echo("Response was:" . $buff . "
    ");
    13 }
    14 socket_close($socket);
  • 相关阅读:
    经典哦,男女3.8,8.3
    在web窗体设计器中未能加载该文件
    使用客户端脚本
    C#的数据类型
    实验下cookie
    C#中Split分隔字符串的应用
    未将对象引用设置到对象的实例
    System.StackOverflowException 的异常;jit调试失败
    DataGrid中添加删除确认对话框 多种实现
    常用正则表达式
  • 原文地址:https://www.cnblogs.com/xcc2016/p/5802875.html
Copyright © 2020-2023  润新知