JAVA TCP SOCKET 关于 输入输出流 的问题

zhentengai 2010-03-12 10:31:16
Socket s;
try {
s = new Socket(ip,2000);
OutputStreamWriter output=new OutputStreamWriter(s.getOutputStream());


char version=0; //版本号
String fileName="byte.xml"; //文件名
int fileNameLength=fileName.length(); //文件长度

// int nameLength=(char) file.length();
byte []data=new ParseTreeToXml().parseTreeToXml(tree, "d:\\test\\", fileName); //要发送的数据
int dateLength=data.length; //发送的数据长度




output .write(version); //
output.write(fileNameLength);
output.write(fileName);
output.write(dateLength);
// output.write(data);
output.flush();



接收端 代码如下:

FileOutputStream fileNAMES=new FileOutputStream ("d:\\test.xml"); //写入文件
while(true) {
Socket s = ss.accept();
InputStream r = s.getInputStream();
DataInputStream input=new DataInputStream(r);
byte[] b=new byte[1024];


while(r.read()>-1){
input.read(b, 0, b.length);

String tr=new String(b); //把字节转换成字符串

System.out.println(tr);
fileNAMES.write(b); //把读取的内容写入文件

}
int c = 0;
System.out.println();
r.close();
input.close();



问题如下:

发送的时候 版本号是 int 的 0 但是 我接收的时候 总是发现 字节数不正确 十六进制 显示是


 FF FF 07 00


我的程序哪里写错了,请各位朋友指正一下.如能附上改正的代码.小弟不胜感激!


...全文
135 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhentengai 2010-03-12
  • 打赏
  • 举报
回复
首先 谢谢 nickycheng 的答案.

确实第一个字节是00了,不过读出了很多空的00


不过还是要感谢你!
nickycheng 2010-03-12
  • 打赏
  • 举报
回复
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0) {
fileNAMES.write(buf,0,len);
}

62,624

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧