PHP Socket połączenie (kod przepisany z C++)

0

Witam, napisałem sobie coś takiego, a dokładniej przepisałem w miarę możliwości - nie znam się za bardzo na C++ do PHP:

$message = 'wyslij wiadomosc';
$ip = '127.0.0.1';
$port = 9000;

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($sock, $ip);
socket_connect($sock, $ip, $port);

$len = strlen($message); 
$offset = 0; 
while ($offset < $len){ 
    $sent = socket_write($sock, substr($message, $offset), $len-$offset); 
    if ($sent === false){ 
        // Error occurred, break the while loop 
        break; 
    } 
    $offset += $sent; 
}

Niestety coś to nie chce działać, nie wiem co tutaj może być źle.

Oryginał w C++ (urywki kodu połączenia):

int sock_connect(char *addr, short port, int msec)
{

    int sock;
    struct hostent *host_ptr;
    struct sockaddr_in hostname;

#ifdef _WIN32
    WSADATA wsa;
    WSAStartup(MAKEWORD(2,2),&wsa);
#endif

    sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(sock == -1)
          return SOCK_ERR_CREATE;

    host_ptr = gethostbyname(addr);
    if(host_ptr == NULL)
    {
        host_ptr = gethostbyaddr(addr, strlen(addr), AF_INET);
        if(host_ptr == NULL)
        {
            sock_close(&sock);
            return SOCK_ERR_RESOLVE;
        }
    }

    hostname.sin_family = AF_INET;
    hostname.sin_port = htons(port);

    memcpy(&hostname.sin_addr, host_ptr->h_addr, host_ptr->h_length);

    
    sock_nonblock(&sock);

    connect(sock, (struct sockaddr*) &hostname, sizeof(hostname));

    if(sock_select(&sock, msec, WRITE) <= 0)
    {
        sock_close(&sock);
        return SOCK_TIMEOUT;
    }

    if(!sock_isvalid(&sock))
    {
        sock_close(&sock);
        return SOCK_INVALID;
    }

    return sock;
}


int sock_send(int *s, char *buf, int len, int msec)
{
    int rc;
    int sent = 0;
    int error;

    while(sent < len)
    {
        rc = sock_select(s, 60000, WRITE); //check if socket is connected
        if(rc == 0)
        {
            printf("select returned 0\n");
            fflush(stdout);
            return SOCK_TIMEOUT;
        }

        if(rc == -1)
        {
            printf("select returned -1\n");
            fflush(stdout);
            return SOCK_TIMEOUT;
        }

        if((rc = send(*s, buf+sent, len-sent, 0)) < 0)
        {
            error = errno;
            if(error != EWOULDBLOCK)
            {
                printf("send errno: %d\n", error);
                fflush(stdout);
                return SOCK_TIMEOUT;
            }
            rc = 0;
        }

        sent += rc;
    }
    return sent;
}

Pozdrawiam i liczę na pomoc.

0

Zdefiniuj "Nie działa".

U mnie nie działa na przykład z powodu PHP Fatal error: Call to undefined function socket_create(), ponieważ rozszerzenie php_sockets.dll nie jest włączone w php.ini.

A potem działa, ale wywraca błąd, bo socket_bind() nie jest potrzebne.

1 użytkowników online, w tym zalogowanych: 0, gości: 1