我试图使用C从A Java客户端向C服务器发送一些字符串.
首先,我发送字符串的长度.然后,我在C中手动分配内存
最后我逐个字符地发送字符串.
问题有时我得到正确的字符串,有时我得到整个字符串额外的其他未知字符(就像我分配比我得到的更多).
这是Java代码:
protected void send(String data){
short dataLength=(short)data.length();
try {
out.write(dataLength);
for (int i=0; i
{
out.write(data.getBytes()[i]);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这是C代码:
void read4(int sock, int *data)
{
char dataRecv;
char* memoireAllouee=NULL;
int stringLength;
int i=0;
recv(sock, (char*)&dataRecv, sizeof(dataRecv), 0) ;
*data = dataRecv;
stringLength=dataRecv;
memoireAllouee=malloc(sizeof(char)*stringLength);
if (memoireAllouee==NULL)
{
exit(0);
}
for (i=0;i
{
recv(sock, (char*)&dataRecv, sizeof(dataRecv), 0) ;
*data = dataRecv;
memoireAllouee[i]=dataRecv;
}
printf("
%d
",stringLength);
printf("
%s
",memoireAllouee);
}
如果你认为这种方法不是最优的,你可以帮助我加快速度吗?