将字符串从Java发送到C(套接字)
我正在尝试使用C从Java客户机向C服务器发送一些字符串。 首先,我发送字符串的长度。然后,我在C中手动分配内存 最后我一个字符一个字符地发送字符串 问题是,有时我得到正确的字符串,有时我得到整个字符串+额外的其他未知字符(就像我分配的比我得到的更多) 以下是Java代码:将字符串从Java发送到C(套接字),java,c,sockets,tcp,Java,C,Sockets,Tcp,我正在尝试使用C从Java客户机向C服务器发送一些字符串。 首先,我发送字符串的长度。然后,我在C中手动分配内存 最后我一个字符一个字符地发送字符串 问题是,有时我得到正确的字符串,有时我得到整个字符串+额外的其他未知字符(就像我分配的比我得到的更多) 以下是Java代码: protected void send(String data){ short dataLength=(short)data.length(); try { out.write(dataLen
protected void send(String data){
short dataLength=(short)data.length();
try {
out.write(dataLength);
for (int i=0; i<data.getBytes().length ;i++)
{
out.write(data.getBytes()[i]);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
受保护的无效发送(字符串数据){
short dataLength=(short)data.length();
试一试{
out.write(数据长度);
对于(int i=0;iprotectedvoid发送(字符串数据){
short dataLength=(short)data.length();
试一试{
out.write(数据长度);
(int i=0;i回答第二个问题:
for (int i=0; i<data.getBytes().length ;i++)
{
out.write(data.getBytes()[i]);
}
及
for(i=0;i@trutheality:如果您将每个例程中涉及的行复制并粘贴到一个答案中,这将是一个非常好的答案。@sarnold我查看了文档,发现out
可能是一个,如果是,匹配的方法是write(int)
将int
的底部8位写入流。这就解释了为什么正确传输长度(或者接近它,如果它真的发送short
,情况会更糟)。这也意味着转换为short
是完全没有必要的,或者是试图在存储长度的临时变量中节省16位空间。@truthreality:你的答案是wright!我很愚蠢,我没有注意C端的字符。所以会发生这样的情况:当我发送一个字符串127个字符时,m任何随机情况都会发生…(写字符串和其他奇怪的字符,根本不写字符串…)再次感谢你。啊,还有一件事,请(为其他人)提供信息。我已将短字符转换为2字节的数组,然后发送它。
protected void send(String data){
short dataLength=(short)data.length();
try {
out.write(dataLength);
for (int i=0; i<data.getBytes().length ;i++)
{
out.write(data.getBytes()[i]);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int i=0; i<data.getBytes().length ;i++)
{
out.write(data.getBytes()[i]);
}
out.write(data.getBytes());
for (i=0;i<stringLength;i++)
{
recv(sock, (char*)&dataRecv, sizeof(dataRecv), 0) ;
*data = dataRecv;
memoireAllouee[i]=dataRecv;
}
int offset= 0;
while (offset < stringLength)
{
int count = recv(sock, &memoireAllouee[offset], stringLength-offset 0) ;
if (count == 0)
// premature EOS .. do something
break;
if (count == -1)
// Error ... do something
break;
offset += count;
}