2011-04-04 139 views
0

我目前正在编写两个项目,必须通过TCP彼此进行通信,客户端必须使用System :: Net :: Sockets ,以及使用C++ winsock的服务器。很长一段时间以来,我一直使用这个可爱的函数来接收winsock中的文本,客户端首先发送消息长度,然后发送消息。我不想用这个函数在服务器端改变任何东西,但是用.NET我会做任何事情。这是我的尝试。客户端/服务器与系统.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. 你要发送的字符串长度as一个字符串,但服务器正在以二进制形式读取它。
  2. 服务器假定recv将始终读取请求的字节数。这是错误的; recv可能会返回0(如果另一方已正常关闭连接),范围[1,len](如果某些数据已成功接收)或SOCKET_ERROR(如果有错误)范围内的任何值。