0

我一直在尝试创建套接字并将其绑定到 localhost127.0.0.1并尝试使用 Microsoft 的 telnet 服务连接到它,但是无论何时连接到指定的地址和端口,都会出现以下错误。

PHP 警告:socket_write():无法写入套接字 [0]:不允许发送或接收数据的请求,因为套接字未连接并且(当 s 使用 sendto 调用在数据报套接字上结束时)未提供地址.

socket_read 返回了一个类似的错误,我不明白 telnet 应该可以正常工作,向 localhost 发出 socket_connect 请求。

这是代码:

set_time_limit(0);
$socket=null;
$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if(socket_bind($socket,"127.0.0.1",58)){    
    if(!socket_listen($socket,0)){
        echo "Problem Listening to the socket";
    }do{
        $res=socket_accept($socket);
        $write="\n Hello the connection has been established";  
        if(!socket_write($socket,$write,strlen($write))){
            echo "Problem Reading the and writing to the socket";
            }                   
            do{
            if(!$clientmsg=socket_read($socket,2048,PHP_NORMAL_READ)){
                echo "Error reading Client Msg";
                break;
                    }
            $repsonse= "Thanks for you input";
            socket_write($socket,$response,strlen($response));
            if($nclientmsg=trim($clientmsg)){
                continue;
            }
            if($clientmsg="close"){
                socket_close($socket);
                echo "The socket has been closed as promised Thanks";
                break 3;
                }
            }while(true);
            }while(true);
}else{
    echo "Problem connecting to the socket.Unable to bind to the specified address";
}

谢谢。

4

1 回答 1

0

您的代码在任何地方都没有socket_connect ..您需要在socket_write之前进行socket_connect(对于tcp和telnet .. udp是另一回事)...无论如何,这是连接到telnet服务器的示例代码:

<?php
    $socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if($socket===false){
    throw new Exception("socket_create() failed: reason: " . socket_strerror(socket_last_error()));
}
assert(socket_set_block ( $socket)===true);
assert(socket_bind($socket,0,mt_rand(1024,5000))!==false);//TODO: don't use mt_rand... it has a (small) chance choosing a used address..
if(socket_connect($socket,
'131.252.208.48',7680
)!==true){
       throw new Exception("socket_connect() failed: reason: " . socket_strerror(socket_last_error($socket)));
}
echo "connected!";
$buffer="";
do{
    sleep(1);
    socket_recv($socket,$buffer,100,0);
    echo $buffer;
} while(strlen($buffer)>1);
socket_close($socket);

- 我在这段代码中做了类似的事情https://github.com/divinity76/outcastshit/blob/master/LoginWithPHP.php

于 2015-08-22T15:40:43.347 回答