1

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

但是,当我将套接字服务器上传到我的 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);
?>

我将非常感谢我能得到的任何帮助,并感谢您的时间。

4

1 回答 1

0

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

于 2013-08-08T11:47:41.427 回答