我正在尝试创建服务器和客户端TCP / IP。我想将文件从客户端发送到服务器。我知道我必须以二进制模式打开文件。我将数据(从文件中读取)存储在unsigned char数组中。
我做了一个简单的协议:首先,我在第一个字节添加了一个字符“\ x02”。之后,在数据中,我添加了'|'在每个字符“\ x02”之后。
使用小文本可以正常工作。
我的问题:当我使用包含1024个字符“\ x02”的文本文件进行测试时,进度已损坏。
这是我的客户代码:
FILE *fr = fopen(fpath, "rb");
char rec[32];
int inc = 0;
while(size>0){
unsigned char buffer[1030];
unsigned char data[2070] ;
unsigned char header[1] = {'\x02'};
int bytesRead;
if(size>=1024){
bytesRead = fread(buffer, 1024, 1, fr);
} else {
bytesRead = fread(buffer, size, 1, fr);
}
memmove(sms,header,1);
unsigned char *pch;
int _countHead = 0;
pch = (unsigned char*) memchr(buffer,"\x02",bytesRead);
while(pch != NULL) {
memmove(buffer + (pch-buffer+2),buffer + (pch-buffer+1),bytesRead);
memmove(buffer + (pch-buffer+1), "|", 1);
_countHead ++;
pch = (unsigned char*) memchr(buffer + (pch - buffer + 1),"\x02",bytesRead);
}
memmove(sms,buffer,bytesRead + _countHead);
send (m_socket,(char*) sms, bytesRead + _countHead,0);
recv(m_socket,rec,2,0);
size -= 1024;
inc++;
}
if(NULL != fr){
fclose(fr);
fr = NULL;
}
提前致谢:)
更新
我做了一个新代码作为你的意见:
FILE *fa = fopen(fpath,"rb");
while(size>0){
unsigned char buffer[1024];
unsigned char buff[2048];
unsigned char sms[2064];
int _countHead = 0;
int _countEnd = 0;
if (size >= 1024)
{
bytesRead = fread(buffer,1,1024,fa);
}
else
{
bytesRead = fread(buffer,1,size,fa);
}
memcpy(buff,buffer,bytesRead);
memset(sms,'#',2064);
memset(numstr,'#',7);
memcpy(sms,header,1);
itoa(inc,numstr,10);
memcpy (sms+1,&numstr,7);
unsigned char *pch;
pch = (unsigned char*) memchr(buff,'\x02',bytesRead);
while(pch != NULL)
{
int pos = pch - buff;
memcpy (buff + pos + 2, buff + pos + 1, bytesRead);
memcpy (buff + pos + 1, ext, 1);
pch = (unsigned char*) memchr(buff + pos +1,'\x02',bytesRead - pos);
_countHead ++;
}
pch = (unsigned char*) memchr(buff,'\x03',bytesRead);
while(pch != NULL)
{
int pos = pch - buff;
memcpy (buff + pos + 2, buff + pos + 1, bytesRead);
memcpy (buff + pos + 1, ext, 1);
pch = (unsigned char*) memchr(buff + pos + 1,'\x03',bytesRead);
_countEnd ++;
}
memcpy (sms+8,buff,bytesRead + _countHead + _countEnd);
memcpy (sms + (bytesRead + _countHead + _countEnd + 8),end,1);
memcpy (sms + (bytesRead + _countHead + _countEnd + 9),numstr,7);
send(m_socket,(char*)sms,bytesRead + _countHead + _countEnd + 16 ,0);
recv(m_socket,rec,2,0);
size -= 1024;
}