C ++和PHP套接字连接

时间:2011-11-01 13:34:43

标签: php c++ sockets

我想使用php连接到我的c ++服务器... 到目前为止,我得到了:

Server.cpp

#include <winsock2.h>
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
WSADATA wsaData;
SOCKET mySocket;
SOCKET myBackup;
SOCKET acceptSocket;
sockaddr_in myAddress;


 // setup WSA and socket....     
 if( WSAStartup( MAKEWORD(2, 2), &wsaData ) != NO_ERROR )
  {
    cerr<<"Socket Initialization: Error with WSAStartup\n";
    system("pause");
    WSACleanup();
    exit(10);
}

//Create a socket
mySocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );

if ( mySocket == INVALID_SOCKET )
{
    cerr<<"Socket Initialization: Error creating socket"<<endl;
    system("pause");
    WSACleanup();
    exit(11);
}

myBackup = mySocket;


//bind
myAddress.sin_family = AF_INET;
myAddress.sin_addr.s_addr = inet_addr( "0.0.0.0" );
myAddress.sin_port = htons( 25555 );


if ( bind ( mySocket, (SOCKADDR*) &myAddress, sizeof( myAddress) ) == SOCKET_ERROR )
{
    cerr<<"ServerSocket: Failed to connect\n";
    system("pause");
    WSACleanup();
    exit(14);
}

//listen
if ( listen ( mySocket, 10 ) == SOCKET_ERROR )
{
    cout<<"ERR: ServerSocket: Error listening on socket\n";
    system("pause");
    WSACleanup();
    exit(15);
}
cout<<"srv started. listeninig...\n";

//accept
acceptSocket = accept( myBackup, NULL, NULL );
while ( acceptSocket == SOCKET_ERROR )
{
    acceptSocket = accept( myBackup, NULL, NULL );
}
mySocket = acceptSocket;

cout<<"done.\n";

return 0;
}

和php客户端

<?php
$port = 25555;
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
#socket_bind($socket,'',$port);
socket_connect($socket, '/my_ip/', $port);

echo 'connecting...';
?>

我不知道该怎么做。 c ++服务器只是看不到php客户端...

2 个答案:

答案 0 :(得分:1)

您需要在PHP中进行正确的检查,以确保一切正常。

试试这个:

    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket === false) {
        die("socket_create() failed: Reason: " . socket_strerror(socket_last_error()) . "\n\n");
        return false;
    }

    echo("Attempting to connect to '{$IP}' on port '{$PORT}'");
    $result = socket_connect($socket, $IP, $PORT);
    if ($result === false) {
        echo("socket_connect() failed. Reason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n\n");
        return false;
    } else {
        echo "OK.\n\n";
    }

答案 1 :(得分:0)

检查错误代码......

socket_create

socket_create() returns a socket resource on success, or FALSE on error. 

socket_connect

Returns TRUE on success or FALSE on failure.
The error code can be retrieved with socket_last_error().
This code may be passed to socket_strerror() to get a textual explanation of the error.