【问题标题】:php socket server works only on localhost but not live serverphp 套接字服务器仅适用于本地主机,但不适用于实时服务器
【发布时间】:2018-05-04 06:54:22
【问题描述】:

我有托管域 godaddy 并且我启用了套接字模块,但不工作 此代码仅在本地主机中有效,当我将其上传到服务器时它不起作用。

代码 server.php

<?php
// set some variables
$host = '150.113.178.20';
$port = 5000;

 if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created \n";

// Bind the source address
if( !socket_bind($sock, $host , $port) )
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Could not bind socket : [$errorcode] $errormsg \n");
}

echo "Socket bind OK \n";

if(!socket_listen ($sock , 10))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Could not listen on socket : [$errorcode] $errormsg \n");
}

echo "Socket listen OK \n";

echo "Waiting for incoming connections... \n";

//start loop to listen for incoming connections
while (true) 
{
    //Accept incoming connection - This is a blocking call
    $client =  socket_accept($sock);

    //display information about the client who is connected
    if(socket_getpeername($client , $address , $port))
    {
        echo "Client $address : $port is now connected to us. \n";
    }

    //read data from the incoming socket
    $input = socket_read($client, 1024000);

    $response = "OK .. $input";

    // Display output  back to client
    socket_write($client, $response);
}

当我在 ssh 中执行 server.php 脚本时没有问题

但是当我从 CMD 写入时:

错误日志文件

【问题讨论】:

  • 你检查过错误日志吗?
  • 你确定是那个IP?
  • 这里的代码和图片我只是给你一个例子,但是我确定我的代码中的 IP 地址是正确的。
  • 我建议在代码开头添加error_reporting(E_ALL);ini_set('display_errors', 1); 看看是否有任何错误,可能是端口问题,尝试另一个..
  • 我在终端中执行 server.php 所以 error_reporting(E_ALL);和 ini_set('display_errors', 1);他们没用,我尝试了很多端口,但同样的问题。

标签: php sockets server


【解决方案1】:

经过一番研究,我发现代码是正确的 Godaddy 不打开自定义端口。 该代码不起作用,因为 localhost 与 GoDaddy(或其他托管网站)的安全策略不同。

【讨论】:

  • 那么我们如何在 Godaddy 云中创建 TCP Server
猜你喜欢
  • 2017-11-26
  • 1970-01-01
  • 1970-01-01
  • 2014-08-11
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多