我的socket

1.把php.ini的;extension=php_sockets.dll把前面的逗号去掉,重启服务器。

2.改变环境变量

  找到php目录我的是:

     修改环境变量:

      右击‘我的电脑’--->'属性'---->‘高级’------->'环境变量'------->双击‘path’----->在后面加上;路径

3.下面进入正题:上代码

  //服务器端

<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 *  a.创建端口 socket_create
  b.绑定端口 socket_bind()
  c.监听端口 socket_listen
  d.得到一个通话连接 soket_accept()
  f.写信息(发送信息)soket_write()
  g.读信息(接收信息)soket_read()
  h.关闭通话
 */


set_time_limit(0);

$address = '127.0.0.1';
$port = 18255;

//创建端口
if (($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
    echo 'socket_create()出错原因:' . socket_strerror($socket);
    exit;
}

//绑定端口
if (($bind = socket_bind($socket, $address, $port))<0){
     echo 'socket_bind()出错原因:' . socket_strerror($bind);
    exit;
}

//监听端口

if(($listen = socket_listen($socket, 5))<0){
     echo 'socket_listen()出错原因:' . socket_strerror($listen);
    exit;
}

$flag = 0;

do{
    //得到一个连接
  if(($msgsock = socket_accept($socket))<0){
      echo 'socket_accept()出错原因:' . socket_strerror($msgsock);
     
      break;
  }

  $msg = '<b style="color:red">welcome---friend</b>';

  //发送到客户端
  socket_write($msgsock,$msg,strlen($msg));
   //接收客户端信息
  $recive = socket_read($msgsock, 1024);
  echo '接收客户端的信息:\n'.$recive;



    $flag++;
    if($flag>=10){//假设通信10次
        break;
    }
    socket_close($msgsock);
}while(true);

socket_close($socket);

?>

  //客户端

<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * a.创建端口 socket_create
    b.连接端口 socket_connect
    c.读信息  soket_read()
    d.写信息 soket_write()
 */
set_time_limit(0);

$address = '127.0.0.1';
$port = 18255;
//创建端口
if (($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
    echo 'socket_create()出错原因:' . socket_strerror($socket);
    exit;
}

echo '正在连接服务器......\n';
if(($result=socket_connect($socket, $address, $port))<0){
    echo 'socket_connect()出错原因:' . socket_strerror($result);
    exit;
}

$msg ='think you!!!!!';
if(!socket_write($socket, $msg,strlen($msg))){
    echo 'socket_write()------error';
    exit;
}
while($recive = socket_read($socket, 1024)){
    echo '收到的内容为:'.$recive;
    echo '\n';
}


socket_close($socket);

?>

4.测试

  //服务端

看红线是收到客户端的消息think you!!!

  //客户端

遗憾啊!有乱码

原文地址:https://www.cnblogs.com/lihaolihao/p/2749114.html