我正在尝试从客户端向服务器发送消息,但我遇到的问题是消息不是固定长度,所以我试图在消息之前放置总字节数/字符数。但问题没有解决。我开始在服务器端获得垃圾,这就像客户端不断发送相同的信息,但垃圾更多。
在事情正常之前,我试图在以前的代码中添加一些东西,但是有很多运行时错误和错误。所以我采用了这种方法,这似乎是最好的。
还有2件事, 1-看起来缓冲区没有清空就像继续添加一样,即使它设法读取我在调试代码时可以看到的第一条消息。 2-如何清空我从缓冲区中读取的部分,在我的例子中是mybuffer
Windows 7 Visual C ++ 2010 Express
服务器代码:
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;
}
客户端: 主要(){ 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";
}