使用socket实现简单数据文件传输

使用socket实现局域网中文件数据的简单传输。


public class FileServer {


public static void main(String[] args) {
FileServer fileServer = new FileServer();
fileServer.server();
}

public boolean server() {

try {

//设置serversocket,端口号设置为3336

ServerSocket server = new ServerSocket(3336);

//监听所有访问3336端口的事件

Socket socket = server.accept();

//声明数据输入流,将客户端的数据输入流传入,以便读取数据

DataInputStream inFileName = new DataInputStream(socket.getInputStream());
Date date = new Date();

SimpleDateFormat format = new SimpleDateFormat("hh点mm分ss秒");

//文件名

String fileName = format.format(date)+inFileName.readUTF();

//传入的文件路径名

String savePath = "D:/"+fileName;
System.out.println("文件接收到:"+savePath);
//传入的文件长度
int len = inFileName.readInt();
//文件字符输出流
FileOutputStream outFile = new FileOutputStream(savePath);
int bufferSize = 8192;  
byte[] buf = new byte[bufferSize]; 

int passedlen = 0;

//遍历流中数据,复制文件

while (true) { 
int read = 0;  
if (inFileName != null) { 
read = inFileName.read(buf);  
len = read;
}  
passedlen += read; 
if (read == -1) { 
break;  
}  
System.out.println("文件接收了" + (passedlen * 100 )/len/100 + "%\n"); 
outFile.write(buf, 0, read);  

}  

//遍历完成,将需要关闭的流跟socket关闭

outFile.close();
socket.close();
server.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}

}

}


public class FileClient {


public static void main(String[] args) {
// TODO Auto-generated method stub
FileClient client = new FileClient();
client.send("c:/ex18_3.txt","127.0.0.1",3336);
}


public void send(String file,String path,int num) {
try {
File sendFile = new File(file);
Socket socket = new Socket(path,num);
DataOutputStream out1= new DataOutputStream(socket.getOutputStream());
out1.writeUTF(sendFile.getName()); 
out1.flush();  

out1.writeInt((int) sendFile.length());
out1.flush();  

DataInputStream inputStream = new DataInputStream(new FileInputStream(sendFile));  
DataOutputStream outFile= new DataOutputStream(socket.getOutputStream());
int bufferSize = 8192;  
byte[] buf = new byte[bufferSize]; 

//跟服务器端相同,将文件遍历输入到数据流中

while (true) { 
int read = 0; 
if (inputStream != null) { 
read = inputStream.read(buf);  
}  
if (read == -1) { 
break;  
}  
outFile.write(buf, 0, read);  
}  
inputStream.close();
outFile.flush(); 

//out1.flush(); 
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值