PHPÇëÇóSocket½Ó¿Ú²âÊÔʵÀý

5年以前  |  阅读数:417 次  |  编程语言:PHP 

ʹÓÃphp¶ÁÈ¡socket½Ó¿ÚµÄÊý¾Ý£¬Í¨¹ýphp´«µÝÇeÇo½¨ºÍÇeÇo²ÎÊý£¬µÃµ½*µ»Ø½a¹u

PHPÎļþ£º


    <?php
    class Test{
      const IP='127.0.0.1';
      const port=10003;
      public static function main(){
        header("Content-type:text/html;Charset=UTF-8");
        $socket=new Test();
        $result=$socket->connSocket("getmaillist\r\n{'id':2}\r\n");
        echo $result;
      }
      private function connSocket($str){
        $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
        $res=@socket_connect($socket,self::IP,self::port);
        if(!$res){
          return;
        }
        socket_write($socket,$str);
        $result="";
        while($data = socket_read($socket,1024)){
          $result.=$data;
        }
        socket_close($socket);
        return $result;
      }
    }
    Test::main();

JavaµÄSocket*þÎñ¶Ë£º


    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;

    public class Test {
      public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(10003);

        while (true) {
          Socket socket = serverSocket.accept();

          InputStream is = socket.getInputStream();
          byte[] b = new byte[1024];
          int len = is.read(b);
          String inputString = new String(b, 0, len);
          PrintWriter pw=new PrintWriter(socket.getOutputStream(),true);
          String result="";

          //´¦Ài*¢À´µÄÊý¾Ý
          if(inputString.contains("\r\n")){
            String[] params=inputString.split("\r\n");
            if(params[0].equals("getmaillist")){
              String maillist=getmaillist();
              result="ÇeÇo*½*¨£º"+params[0]+",ÇeÇo²ÎÊý£º"+params[1]+",ÇeÇo½a¹u£º"+maillist;
            }else{
              result="*Ç*¨²ÎÊý2";
            }
          }else{
            result="*Ç*¨²ÎÊý1";
          }

          pw.println(result);
          socket.close();
        }
      }
      public static String getmaillist(){
        return "ÖйuÉϺ£/2015Äe7ÔÂ28ÈÕ¡ª¡ª*þÎñÓÚÖйu¼°È«Ço»ªÈËÉçȺµÄÁiÏÈÔÚÏßýÌa¹«Ë¾ÐÂÀ˹«Ë¾(Nasdaq GS: SINA)¶¨ÓÚÃÀ¹uµ±µØʱ¼a2016Äe8ÔÂ8ÈÕÖÜÒ»¹ÉÊÐÊÕÅ̺o¹«²¼½ØÖÁ2016Äe6ÔÂ30ÈÕµÄ2016µÚ¶þ¼¾¶Èδ¾­Éo¼ÆµÄ²ÆÎñ±¨¸ae¡£Ëaeºo£¬ÐÂÀ˹ÜÀiÍŶӽ«ÓÚÃÀ¹u¶«²¿Ê±¼aÍi10µa10*ÖÕÙ¿ªµç»°»aÒe£¬Í¨±¨¹«Ë¾µÄ²ÆÎñºÍ¾­Óª×´¿o¡£";
      }
    }

Ч¹u£º

ÒÔÉÏÕaƪPHPÇeÇoSocket½Ó¿Ú²aÊÔʵÀý¾ÍÊÇС±a*ÖÏi¸ø´o¼ÒµÄÈ«²¿ÄÚÈÝÁË£¬Ï£ÍuÄܸø´o¼ÒÒ»¸o²Î¿¼£¬Ò²Ï£Íu´o¼Ò¶a¶aÖ§³Ö½Å±¾Ö®¼Ò¡£

 相关文章:
PHP分页显示制作详细讲解
SSH 登录失败:Host key verification failed
获取IMSI
将二进制数据转为16进制以便显示
获取IMEI
文件下载
贪吃蛇
双位运算符
PHP自定义函数获取搜索引擎来源关键字的方法
Java生成UUID
发送邮件
年的日历图
提取后缀名
在Zeus Web Server中安装PHP语言支持
让你成为最历害的git提交人
Yii2汉字转拼音类的实例代码
再谈PHP中单双引号的区别详解
指定应用ID以获取对应的应用名称
Python 2与Python 3版本和编码的对比
php封装的page分页类完整实例