0

我正在尝试将消息从客户端发送到服务器,但我遇到了消息不是固定长度的问题,因此我尝试将字节/字符的总数放在消息之前。但问题没有解决。我开始在服务器端收到垃圾,就像客户端不断发送相同的信息但垃圾更多。

在一切正常之前,直到我试图向以前的代码添加一些东西,但有很多运行时错误和错误。所以我采用了这种方法,这似乎是最好的。

还有 2 件事,1- 似乎缓冲区没有像继续添加一样清空,即使它设法读取了我在调试代码时可以看到的第一条消息。2-如何清空我从缓冲区中读取的部分,在我的情况下是 mybuffer

Windows 7 Visual C++ 2010 速成版

服务器代码:

 char * GetMessage(int x, char arry [])
 {
char * msg = NULL;
msg = new char[x];
ZeroMemory(msg,x);

for(int i = 1; i <= x; i++)
{
    msg[i-1] = arry[i];
}

return msg;
  }

 void main(){

  char Filename[20];
            char Direction[4];
            char Type[1];
            bool FileExistOnClient;
            fstream fFile;
            FILE * iiFile;
            int strlength;
            char Hostname[20];
            int count = 0 ;
            char * ptr;


            ibytesrecv=0; 
            ZeroMemory(mybuffer,strlen(mybuffer));
            if((ibytesrecv = recv(s1,mybuffer,100,0)) == SOCKET_ERROR)
                throw "Receive failed\n";
            ptr = &mybuffer[0];
            count = atoi(ptr);
            sprintf(Hostname , GetMessage(count,mybuffer));
            cout <<mybuffer <<"\n";
            cout <<"Hostname is:" << Hostname << endl;
  }

客户端:main(){ ZeroMemory(mybuffer,strlen(mybuffer));

    mybuffer[0] = strlen(localhost)+48;
    strcat(mybuffer,localhost);
    ibytessent=0;    
    ibufferlen = strlen(mybuffer)  ;
    ibytessent = send(s,mybuffer,ibufferlen,0);
    if (ibytessent == SOCKET_ERROR)
        throw "Send failed\n";  


    //Send File name
    //ZeroMemory(mybuffer,strlen(mybuffer));
    mybuffer[strlen(mybuffer) ] = strlen(Filename)+48;
    strcat(mybuffer,Filename);
    ibytessent=0;    
    ibufferlen = strlen(mybuffer);
    ibytessent = send(s,mybuffer,ibufferlen,0);
    if (ibytessent == SOCKET_ERROR)
        throw "Send failed\n";  
 }
4

0 回答 0