java多线程网络传输文件非同步.docx
《java多线程网络传输文件非同步.docx》由会员分享,可在线阅读,更多相关《java多线程网络传输文件非同步.docx(16页珍藏版)》请在冰点文库上搜索。
java多线程网络传输文件非同步
用socket发送xml文档,把生成的xml文档转化成字符流输出
Socketc=newSocket(host,port)
PrintWriterpw=newPrintWriter(newOutuputStreamWriter(c.getOutputStream()),true);
Filef=newFile(xml);
BufferedReaderbr=newBufferedReader(newFileReader(f));
Stringline;
while((line=br.readLine())!
=null)
pw.println(line);
pw.close();
br.close();
java多线程网络传输文件(非同步)
利用Socket套接字进行面向连接通信的编程。
客户端读取本地文件并发送;服务器接收文件并保存到本地文件系统中。
使用说明:
请将TransferClient,TransferServer,TempFile三个类编译,他们的类包是FileServer.
客户端:
修改TransferClient:
serPort,serIP,filePath,blockNum,的值来符合您机器的系统环境;或者用命令行
格式:
javaFileServer.TransferClient文件路径+文件名服务器IP地址端口线程数
C:
\>javaFileServer.TransferCliente:
\GREbulletin.pdf192.168.1.10520085
服务端:
修改TransferServer:
serPort,tempFolder的值来符合您机器的系统环境;或者用命令行
格式:
javaFileServer.TransferServer端口文件夹路径
C:
\>javaFileServer.TransferServer2008F:
\tempFolder
文件传输服务端---------------------------------------------------------
packageFileServer;
importjava.io.DataInputStream;
importjava.io.DataOutputStream;
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.io.RandomAccessFile;
import.ServerSocket;
import.Socket;
import.SocketException;
/**
*DescriptionSocket文件传输服务端
*默认支持多线程传输,未支持断点续传,未支持内网UDF传输
*CreationDate07-08-20089:
00
*@author
*@version1.0
*/
publicclassTransferServer{
/**
*@paramargs[0]端口默认2008(例:
2008)
*@paramargs[1]接收文件存放路径,默认:
和FileServer同一目录\ServerReceive
* (例:
x:
\example\example\)
*/
publicstaticvoidmain(String[]args){
try{
intserPort=2008;//服务器默认端口2008
StringtempFolder=System.getProperty("user.dir")+"\\ServerReceive";//临时文件夹,用于存放接收文件
ServerSocketss=null;//设定Socket
if(args.length<1||null==args){
ss=newServerSocket(serPort);
}else{
//检测输入端口是否正确
if(args[0].replaceAll("\\D","")!
=""){
serPort=Integer.parseInt(args[0].replaceAll("\\D",""));
}else{
System.out.println("输入的端口有错误,使用系统默认端口");
}
ss=newServerSocket(serPort);
if(args[1].length()>0){
tempFolder=args[1];
}
}
System.out.println("WelcometoTransferServer");
System.out.println("服务器启动,监听端口"+ss.getLocalPort());
System.out.println("服务器临时文件路径:
"+tempFolder);
while(true){
Sockets=ss.accept();
newThread(newServerThread(s,tempFolder)).start();
}
}catch(IOExceptione){
e.getMessage();
System.out.println("服务器端口被占用,或其他问题.");
}
}
}
/**
*Description服务器线程
*@author卢俊宇
*@paramtempFolder接收文件存放路径,默认:
TransferServer.class所在目录\ServerReceive
* (例:
x:
\example\example\)
*@version1.1
*/
classServerThreadimplementsRunnable{
Sockets;//实例化socket类
privateStringtempFolder;//临时文件夹名
publicServerThread(Sockets,StringtempFolder){
this.s=s;
this.tempFolder=tempFolder;
}
@SuppressWarnings("deprecation")
publicvoidrun(){
try{
InputStreamins=s.getInputStream();
OutputStreamouts=s.getOutputStream();
DataInputStreamdis=newDataInputStream(ins);
DataOutputStreamdos=newDataOutputStream(outs);
//取得线程ID
StringSerID="SerID-"+Thread.currentThread().getId();
while(true){
try{
StringinStr=dis.readUTF();
//接收到的文件包含头信息
if(inStr!
=null){
//对收到的socket包过滤出文件信息
if(inStr.contains("ClientInfo")){
System.out.println(SerID+"getFileInfo!
");
//文件名字
StringfName=newString(inStr.replaceAll(
"(.+)|(<\\/FileName>\\S+)","")
.toString().getBytes("utf-8"),"utf-8");
//文件总长度
StringfSize=newString(inStr.replaceAll(
"(.+)|<\\/FileLength>","")
.toString().getBytes("utf-8"),"utf-8");
System.out.println("size:
"+fSize);
longSize=Long.parseLong(fSize);
//区块起始长度
StringfPs=newString(
inStr
.replaceAll(
"(.+)|(\\S+)",
"").toString().getBytes(
"utf-8"),"utf-8");
System.out.println("PS:
"+fPs);
//区块结束长度
StringfPe=newString(
inStr
.replaceAll(
"(.+)|(\\S+)",
"").toString().getBytes(
"utf-8"),"utf-8");
System.out.println("PE:
"+fPe);
longPointS=Long.parseLong(fPs);//分块头
longPointE=Long.parseLong(fPe);//分块尾
System.out.println("SourceFileName:
"+fName);
FiletempF=newFile(tempFolder,fName);
if(!
tempF.exists()){
//检测目标文件夹是否存在
if(newFile(tempFolder).isDirectory()){
TempFile.creat(tempF,Size);//如果临时文件不存在就建立
}else{
booleancreat=newFile(tempFolder).mkdirs();
if(creat){
TempFile.creat(tempF,Size);//如果临时文件不存在就建立
}else{
System.out.println("Error:
Systemcannotcreatfolder!
");
System.out.println(SerID+"exits");
dis.close();//关闭包类
dos.close();//关闭输出流
s.close();//关连接
Thread.currentThread().stop();
}
}
}
//返回服务器准备好了
StringSerReady=SerID+"ServerReady=1";
dos.writeUTF(SerReady);//返回服务器信息
dos.flush();
//取得客户端发送标志"SendStart"
if(dis.readUTF().equals("SendStart")){
//随机读写文件(适应多线程方式)
RandomAccessFilefos=newRandomAccessFile(
tempF.getPath(),"rw");
longcurPoint=PointS;//文件指针起点
longendSet=PointE;//文件指针终点
longnowSize=0;//已读/写字节
byte[]buffer=newbyte[1024];//建立缓冲区
while(curPoint intlength=0;
try{
if((endSet-curPoint+1)<1024){
fos.seek(curPoint);//寻找写入位置
byte[]bufferM=newbyte[(int)(endSet
-curPoint+1)];//调整缓冲区大小
length=ins.read(bufferM);//读取bufferM缓冲socket流
try{
fos.write(bufferM);//将取得的socket流写入文件
dos.writeUTF("SerGotIt");//返回服务器信息
dos.flush();
curPoint+=length;//文件指针增加
nowSize+=length;
fos.close();
//向发送接收结束标志
dos.writeUTF("ReciveEnd");
dos.flush();
System.out.println(SerID
+"isreceiveok.");
break;
}catch(IOExceptione){
e.printStackTrace();
}
}else{
fos.seek(curPoint);
length=ins.read(buffer);
}
}catch(IOExceptione){
e.printStackTrace();
System.out.println(SerID+"isabnormallyclosed.");
break;
}
if(length==buffer.length){
//将缓冲区字节写入文件
try{
System.out
.println(SerID
+"receive"
+buffer.length
+"bytes.");
fos.write(buffer);
dos.writeUTF("SerGotIt");//返回服务器信息
dos.flush();
curPoint+=buffer.length;//指针+1024
nowSize+=buffer.length;
System.out.println(SerID+"指针位置"
+curPoint);
System.out.println(SerID
+"线程size写入进度:
"+nowSize);
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
}
}
//接收到客户端结束标志,跳出循环
if(dis.readUTF().equals("SendEnd")){
System.out.println("服务器接收完毕");
break;
}
}catch(SocketExceptions){
//s.printStackTrace();
//客户端非正常退出处理
System.out.println(SerID+"isabnormallyclosed.");
break;
}
}
dis.close();//关闭包类
dos.close();//关闭输出流
s.close();//关连接
System.out.println(SerID+"exited.");
}catch(IOExceptione){
e.printStackTrace();
}
}
}
文件传输客户端
-----------------------------------------------------------
packageFileServer;
importjava.io.DataInputStream;
importjava.io.DataOutputStream;
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.io.RandomAccessFile;
import.Socket;
import.InetAddress;
import.UnknownHostException;
importjava.text.SimpleDateFormat;
importjava.util.Date;
/**
*DescriptionSocket文件传输客户端(默认支持多线程传输,未支持断点续传,未支持内网UDF传输)
*CreationDate07-08-20089:
00
*@author卢俊宇
*@version1.0
*/
publicclassTransferClient{
/**
*Description文件传输客户端
*
*@paramargs[0]
* 文件路径+文件名(例:
x:
\example\example.class)
*@paramargs[1]
* 服务器IP地址(例:
192.168.1.1)
*@paramargs[2]
* 端口默认2008(例:
2008)
*@paramargs[3]
* 区块长度默认5(例:
5)
*/
publicstaticvoidmain(String[]args){
intserPort=2008;//默认连接端口2008;
intblockNum=5;//文件区块数量(同时决定线程数)
StringserIP="192.168.1.105";//服务器IP
StringfilePath="e:
\\1.rar";//欲发送文件路径+文件名
if(args.length<1||null==args){
System.out.println("采用默认配置连接");
}else{
if(args[0].length()>0){
filePath=args[0];
}
if(args[1].length()>0){
serIP=args[1];
}
if(args[2].length()>0){
serPort=Integer.parseInt(args[2]);
}
if(args[3].length()>0){
blockNum=Integer.parseInt(args[3].replaceAll("\\D",""));
}
}
System.out.println("文件路径:
"+filePath);
System.out.println("连接IP:
"+serIP);
System.out.println("连接端口:
"+serPort);
System.out.println("线程数:
"+blockNum);
//取得文件信息
Filesource=newFile(filePath);
if(!
source.exists()){
System.out.println("要传输的文件不存在!
");
System.exit(0);
}
longfSize=source.length(