2011-04-04 14 views
0

現在、TCPを介して通信する2つのプロジェクトを作成していますが、クライアントはSystem :: Net :: Sockets 、およびC++ winsockを使用しているサーバー。長い間、私はこの素敵な関数を使って、クライアントがメッセージの長さを最初に送信し、次にメッセージを送信するテキストをwinsockで受信しています。私はこの機能でサーバ側で何かを変更する必要はありませんが、.NETを使用して何かを行います。これが私の試みです。クライアントとしてSystem .NETソケットを使用し、サーバーにC++ winsockを持つクライアント/サーバー

bool WinSockObject::receiveText(std::string &out) 
{ 
    //Create a temporary buffer to work with 
    char buf[4096]; 
    //Stores textLength of incoming data 
    long textLength = 0; 
    //Receive the textLength that was sent first 
    _result = ::recv(
     _socket, //socket we are receiving on 
     reinterpret_cast< char *>(&textLength), //the length of the incoming text 
     sizeof(textLength), //number of bytes 
     0 //no additional flags necessary 
    ); 
    //Make sure we got the text length 
    if (_result == SOCKET_ERROR) 
    { 
     set_error("Unable to receive text length."); 
     return false; 
    } 
    //Convert the textLength back to host bytes 
    textLength = ::ntohl(textLength); 
    //Receive the actual message 
    _result = ::recv(
     _socket, //socket we are receiving on 
     buf, //the input buffer 
     textLength, //text length 
     0 //no additional flags are necessary 
    ); 
    //Make sure we got the actual message 
    if (_result == SOCKET_ERROR) 
    { 
     set_error("Unable to receive text."); 
     return false; 
    } 
    //Manually terminate the buffer 
    buf[textLength] = '\0'; 
    //Copy the buffer to the output string 
    out.append(buf); 
    return true; 
} 

しかし、私は、私は簡単な読書の後に見る二つの問題があり、最初のメッセージ

Socket^ s = gcnew Socket(
    AddressFamily::InterNetwork, 
    SocketType::Stream, 
    ProtocolType::Tcp 
); 
s->Connect(server, port); //message to send 
String^ howdy = "howdy"; 
int strLength = howdy->Length; //length of message 
String^ length = strLength.ToString(); //convert it to String 
//get the bytes 
array<Byte>^msgLength = Encoding::ASCII->GetBytes(length); 
//send the message length 
int bytes = s->Send(msgLength); 
//send the actual message 
array<Byte>^msg = Encoding::ASCII->GetBytes(howdy); 
bytes = s->Send(msg); 

答えて

2

を長さを送信立ち往生しています:

  1. あなたは文字列の長さを送っているが、 として文字列ですが、サーバーはバイナリとしてそれを読み取ります。
  2. サーバーでは、recvが要求されたバイト数を常に読み込むと想定しています。これは間違っています; recvは0(相手側が正常に接続を終了した場合)、[1、len](データが正常に受信された場合)、SOCKET_ERROR(エラーがあった場合)のいずれかの値を返すことがあります。
関連する問題