你好 readLong()
的 readLong()
方法遇到了一些问题当我通过 DataOutputStream.writeLong()
输出一个值时,它是正确的值,但是当它被发送时它比应该的大得多,我的代码都在一个可运行的语句中所以程序没有冻结
这是客户
socket = new Socket(ipAddress, Port);
bos = new BufferedOutputStream(socket.getOutputStream());
dos = new DataOutputStream(bos);
File f = new File("C:/Users/lukeLaptop/Downloads/RemoveWAT22.zip");
long length = f.length();
dos.writeLong(length);
String name = f.getName();
dos.writeUTF(name);
FileInputStream fis = new FileInputStream(f);
bis = new BufferedInputStream(fis);
int theByte = 0;
while ((theByte = bis.read()) != -1) {
bos.write(theByte);
}
bis.close();
dos.close();
服务器端
ServerSocket server = new ServerSocket(8080);
while (true) {
socket = server.accept();
System.out.println("Got a client !");
bis = new BufferedInputStream(socket.getInputStream());
dis = new DataInputStream(bis);
int filesCount = dis.readInt();
long fileLength = dis.readLong();
//String fileName = dis.readUTF();
File f = new File("C:/test/here/test.zip");
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
for (int j = 0; j < fileLength; j++) {
bos.write(bis.read());
}
bos.close();
dis.close();
编辑
如果任何人可以帮助我使用代码,我非常感谢我是套接字的新手,我对事情感到有些困惑,我想要的是使用dataoutputstream的writeLong方法发送文件的长度并发送使用writeUTF的名称,但我不知道发生了什么以及如何解决它
2 回答
问题是方法
writeUTF
.javadoc说:
但是你使用自己的长度编码,只需要字符串包含的字符数 . 它不使用字符串的编码长度 .
如果使用DataInputStream.readUTF()来读取字符串,则不必使用自己的长度编码 .
服务器发送:
然后是文件 .
客户读到这个:
然后是文件 .
所以你正在阅读一个你根本没有发送的
filesCount
,而不是正在阅读你发送的fileName
. 那怎么可能有用呢?如果您没有准确地阅读您发送的内容,使用补充方法,它将无法正常工作 .