尝试连接到socket php时无法分配请求的地址

时间:2017-09-16 00:00:38

标签: php

所有这些代码都在我的本地计算机上运行

您好。

我正在尝试学习如何正确使用套接字。

我创建了两个脚本,如下:

socket.php:

<?php

$address = "10.0.1.13";
$port = 19132;

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

if($socket === false){
    console("Failed to create socket.");
    exit(1);
}

if(socket_bind($socket, $address, $port) === false){
    console("CANNOT BIND SOCKET -BYE!");
    exit(1);
}

$stop = false;
$start = microtime(true);

console("Socket started ($address) : $port");

while(!$stop){
}

socket_close($socket);

console("Script stopped.");

function console($message){
    echo $message . "\n";
}

?>

reader.php:

<?php

$address = "10.0.1.13";
$port = 19132;

/* Allow the script to hang around waiting for connections. */
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush();

if (($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if(socket_connect($socket, $address, $portph) === false){
    console("CANNOT CONNECT SOCKET -BYE!");
    exit(1);
}

//socket_set_nonblock($socket);

console("success!");

function console($message){
    echo $message . "\n";
}

?>

目标是运行socket.php,并让reader.php连接到套接字。虽然,我总是通过reader.php获得Can't assign requested address when trying to connect to socket。我不明白我做错了什么。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

根据PHP.net

body {
  font-family: Arial;
  font-size: 12px;
}

.area-drop {
  border: 1px dashed #000;
  width: 300px;
  min-height: 150px;
  text-align: center;
  margin-top: 50px;
  overflow: auto;
}

i.fa {
  margin-right: 5px;
}

.drag-item {
  display: inline-block;
  background-color: #f2f2f2;
  width: auto;
  height: auto;
  line-height: 1em;
}

.drag-item:not(:first-child) {
  margin-left: 15px
}

你可以参考 - [http://php.net/manual/en/function.socket-bind.php][1]