模拟的过程是:A 给 B 发送一个文件。
A 是发送端, B 是接收端。
使用tcp套接字。
使用了:
ServerSocket ss = new ServerSocket(int 端口号);//接收端
Socket s = ss.accept();//接收端
Socket s=new Socket(String IP地址, int 端口);//发送端
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(String 文件路径+文件名));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(String 文件路径+文件名));
文件路径格式可以是:
"D:\\....\\....\\文件名"
比特数组:
byte[] buf=new byte[1024];
循环读取
int b;
while((b=bis.read(buf))!=-1){
fos.write(buf,0,b);
fos.flush();
}
发送端 A:
BufferedInputStream 通过new FileInputStream()方法 从本地读取一个文件,BufferedOutputStream 中的FileOutputStream 实例是通过 s.getOutputStream() 方法获得的,要发送到网络中某个主机。
接收端 B:
与发送端相反,或者说相对应。
BufferedInputStream 中的 FileInputStream 通过 s.getInputStream() 获得,从网络中获取,BufferedOutputStream 通过 new FileOutputStream()方法 把文件写到本地路径。
代码:
发送端:
try {
Socket s=new Socket("127.0.0.1",端口);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\file\\tee"));
BufferedOutputStream fos = new BufferedOutputStream(s.getOutputStream());
byte[] buf=new byte[1024];
int b;
while((b=bis.read(buf))!=-1){
fos.write(buf,0,b);
fos.flush();
}
fos.close();
bis.close();
} catch (IOException exception) {
exception.printStackTrace();
}
接收端:
try {
ServerSocket ss = new ServerSocket(端口);
Socket s = ss.accept();
BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream("D:\\otherfile\\tee"));
byte[] buf=new byte[1024];
int b;
while((b=bis.read(buf))!=-1){
fos.write(buf,0,b);
fos.flush();
}
fos.close();
bis.close();
} catch (IOException exception) {
exception.printStackTrace();
}