socket 问题

jhswlwm 2016-07-27 10:55:12
我遍历了一下文件夹 然后为什么只发送了一个
package baozha;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class ClientTcpSend {

public static void main(String[] args) {
int length = 0;
byte[] sendByte = null;
Socket socket = null;
DataOutputStream dout = null;
FileInputStream fin = null;
try {
try {
File file = new File("K:\\a");
File[] files = file.listFiles();
for(int i=0; i<files.length; i++){
socket = new Socket();
socket.connect(new InetSocketAddress("127.0.0.1", 33456),1000 * 1000);
dout = new DataOutputStream(socket.getOutputStream());
System.out.println(files[i].getName());
System.out.println(files.length);
fin = new FileInputStream(files[i]);
System.out.println(fin);
sendByte = new byte[1024];
dout.writeUTF(files[i].getName());
while((length = fin.read(sendByte, 0, sendByte.length))>0){
dout.write(sendByte,0,length);
dout.flush();
}
}
} catch (Exception e) {

} finally{
if (dout != null)
dout.close();
if (fin != null)
fin.close();
/* if (socket != null)
socket.close();*/
}
} catch (Exception e) {
e.printStackTrace();
}
}

}

服务端
package baozha;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTcpListener implements Runnable {

public void run() {

}

public static void main(String[] args) {
try {
final ServerSocket server = new ServerSocket(33456);
Thread th = new Thread(new Runnable() {

public void run() {
while (true) {
try {
System.out.println("开始监听。。。");
Socket socket = server.accept();
System.out.println("有链接");
receiveFile(socket);
} catch (Exception e) {
e.printStackTrace();
}
}

}

});
th.run();
} catch (Exception ex) {
ex.printStackTrace();
}
}

public static void receiveFile(Socket socket) throws IOException {
byte[] inputByte = null;
int length = 0;
DataInputStream din = null;
FileOutputStream fout = null;
try {

while (true) {
din = new DataInputStream(socket.getInputStream());

fout = new FileOutputStream(new File("K:\\aa\\"+din.readUTF()));
inputByte = new byte[1024];
System.out.println("开始接收数据...");
if (din != null) {
length = din.read(inputByte, 0, inputByte.length);
}
if (length == -1) {
break;
}
// System.out.println(length);
fout.write(inputByte, 0, length);
fout.flush();
}
System.out.println("完成接收");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (fout != null)
fout.close();
if (din != null)
din.close();
/* if (socket != null)
socket.close();*/
}
}

}
...全文
127 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
adfldk 2016-07-28
  • 打赏
  • 举报
回复
有没有打印files.length()

62,628

社区成员

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

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