php socket服务器本地VS.在线vps

时间:2013-08-08 11:14:51

标签: php sockets vps

我试图创建一个简单的套接字服务器。 当我在localhost上运行时,一切正常。

但是当我将套接字服务器上传到我的vps并运行它时, 它启动服务器,但尝试写入时没有任何反应。 (client.php在localhost上运行,不知道那是否可行)。

客户端PHP:

<?php

$host = "93.191.155.164";
//localhost: $host = "127.0.0.1";

$port = 4643;

?>

<html>
<head>
    <title>Client</title>
</head>
<body>
    <form method="post">
        <input type="text" name="input" />
        <input type="submit" name="btn" />
    </form>
    <?php
        if(isset($_POST['btn'])){
            if($_POST['input'] != ''){
                $message = $_POST['input'];

                $socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
                socket_connect($socket, $host, $port) or die("Could not connect to server\n");
                socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");

                if (false == (@$result = socket_read($socket, 1024))) {
                    echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
                }else{
                    echo "Svar fra Server  :".$result . "\n";
                }
                socket_close($socket);
            }
        }
    ?>
</body>
</html>

服务器PHP:

<?php

$host    = "0.0.0.0";
$port    = 4643;

set_time_limit(0);

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

if (socket_bind($socket, $host, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}else{
    echo "Binding af port og adresse er OK\n";
}

if (socket_listen($socket, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}else{
    echo "Lytter for inkommende data OK\n";
}

while(true){
// lav en ny socket til at håntere komunikation.
$spawn = socket_accept($socket) or die("Kan ikke acceptere indkommende data\n");


//inputtet fra clienten.
//input indeholder dataen der er sendt fra clienten.
$input = socket_read($spawn, 1024) or die("Kan ikke lease dataen\n");
$output = "Denne besked kommer fra serveren.";

echo $input . " MSG er modtaget.";


socket_write($spawn, $output, strlen($output)) or die("Kunne ikke skrive tilbage\n");

socket_close($spawn);

}

socket_close($socket);
?>

对于我能得到的任何帮助,我都会很有帮助,而且对于你的时间而言,我会很感激。

1 个答案:

答案 0 :(得分:0)

我很确定你有防火墙。尝试在服务器上运行客户端。然后研究iptables。