dou12352 2009-04-07 18:13
浏览 42
已采纳

PHP:socket侦听问题

Here is my code:

<?php

$host = "127.0.0.1";
$portListen = 1234;
$portSend = 1240;


// create socket
$sSender = socket_create(AF_INET, SOCK_STREAM, 0);

socket_connect($sSender, $host, $portListen);

socket_write($sSender, "test", strlen ("test"));


$sListen = socket_create(AF_INET, SOCK_STREAM, 0);
socket_set_option($sListen, SOL_SOCKET, SO_REUSEADDR, 1);

socket_bind($sListen, $host, $portSend);

socket_listen($sListen,1);
$dataSock = socket_accept($sListen);
echo socket_read($dataSock, 3, PHP_NORMAL_READ);

// close sockets
socket_close($sSender);
socket_close($sListen);
?>

I send "test" to another application, it receives, and send back "ack". Problem is, I can only do it once. If I refresh, I get the address is already used error. I tried the solutions suggested on php.net but to no avail. Trying to socket_shutdown() before socket_close() only give me not connected warning, and upon refreshing will give me a never ending loading.

From what I understand the reason socket is not immediately closed is because there is still data in the buffer. But as you can see I explicitly state to listen to only 1 connection. Plus I am only sending 3 characters from my application and reading 3 in this script.

What am I doing wrong?

edit: The reason I'm using 2 sockets is because I cannot listen() after write() which give me socket is already connected error. Skipping listen() and going straight for read() after write() give me invalid argument error.

  • 写回答

3条回答 默认 最新

  • dongsibao8977 2009-04-07 22:57
    关注

    I see, after having a few hours sleep and re-analyzing my code and the documentations, I managed to fix everything. You guys are right, 1 socket is indeed enough and the correct way:

    <?php
    
    $host = "127.0.0.1";
    $portListen = 1234;
    $sSender = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket
    ");
    
    socket_connect($sSender, $host, $portListen) or die("Could not connect
    ");
    
    socket_write($sSender, "test", strlen ("test")) or die("Could not write output
    ");
    
    echo socket_read($sSender, 3, PHP_NORMAL_READ);
    
    socket_close($sSender);
    ?>
    

    So simple!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line