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 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果