2

无法绑定地址 [0]:每个套接字地址(协议/网络地址/端口)通常只允许使用一次....我的 php 服务器页面给出了错误。我尝试了不同的端口号,就像从 cmd 中查看 netstat -an 一样。我也在谷歌上搜索但没有解决方案。我正在使用 wamp 服务器并在本地工作。谢谢 。

<?php
// don't timeout
//echo phpinfo();
set_time_limit (0);
// set some variables
$host = "127.0.0.1";
$port = 1234;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
echo "Waiting for connections...\n";
// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
echo "Received connection request\n";
// write a welcome message to the client
$welcome = "Roll up, roll up, to the greatest show on earth!\n? ";
socket_write($spawn, $welcome, strlen ($welcome)) or die("Could not send connect string\n");
// keep looping and looking for client input
do
{
  // read client input
  $input = socket_read($spawn, 1024, 1) or die("Could not read input\n");
  if (trim($input) != "")
  {
    echo "Received input: $input\n";
    // if client requests session end
    if (trim($input) == "END")
    {
      // close the child socket
      // break out of loop
      socket_close($spawn);
      break;
    }
    // otherwise...
    else
    {
      // reverse client input and send back
      $output = strrev($input) . "\n";
      socket_write($spawn, $output . "? ", strlen (($output)+2)) or die("Could not write output\n");
      echo "Sent output: " . trim($output) . "\n";
    }
  }
} while (true);
// close primary socket
socket_close($socket);
echo "Socket terminated\n";
?>
4

2 回答 2

1

呃……这是在网页上运行的吗?如果是这样,对页面的每次点击都会导致脚本尝试绑定到端口 1234,这不会一次只发生一个。其他人都会死。

如果不是,那么我可以立即想到绑定失败的两个原因:另一个程序已经在使用该端口,或者防火墙阻止了它。后者不应该是 127.0.0.1 的情况,但我见过更奇怪的事情发生。

于 2010-07-31T12:17:24.527 回答
0

发布的代码应该可以工作,至少在这里可以。您确定没有防火墙阻止您打开套接字吗?

没关系,但是在打开套接字时,请指定正确的协议:

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

如果这没有帮助,请尝试循环查找可能工作的侦听端口;也许您之前的尝试仍然阻止了该端口。

for ( $port = 1234; $port < 65536; $port++ )
{
    $result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
    if ( $result )
    {
        print "bind succeeded, port=$port\n";
        break;
    } else {
        print "Binding to port $port failed: ";
        print socket_strerror(socket_last_error($socket))."\n";
    }
}
if ( $port == 65536 ) die("Unable to bind socket to address\n");

如果这解决了您的问题,您可能想要做

socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);

在绑定之前,告诉系统它应该允许重用端口。

于 2010-07-31T14:25:59.957 回答