黑马程序员技术交流社区
标题:
自己写的局域网文件传输工具,CPU使用率偏高,求解
[打印本页]
作者:
周兴中
时间:
2012-6-28 00:14
标题:
自己写的局域网文件传输工具,CPU使用率偏高,求解
本帖最后由 周兴中 于 2012-6-28 00:17 编辑
各功能使用正常,就是CPU使用率偏高,请大侠指点,该如何优化.
由于代码冗长,分段成3段
以下为分段1:
package filetransdemo;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
*class PicClient implements Runnable //客户端
{
private Frame f;
private TextArea infoTa;
private TextField ipTa,fileTa;
private Button fileBut,sendBut,enter;
private FileDialog fileDia;
private File file;
private Label ipLab,fileLab,logLab,info;
private Dialog infoDia;
private DatagramSocket ds;
private DatagramPacket dp;
private List lst;
private String ip;
PicClient(Frame f,TextField ipTa,TextField fileTa,TextArea infoTa,List lst,String ip)
{
this.f = f;
this.ipTa = ipTa;
this.fileTa = fileTa;
this.infoTa = infoTa;
this.lst =lst;
this.ip = ip;
}
public void run()
{
try
{
init();
}
catch (Exception e)
{
throw new RuntimeException("客户端初始化失败");
}
}
public void init() //客户端初始化
{
try
{
infoDia = new Dialog(f,"提示信息",true);
infoDia.setBounds(600,300,300,80);
infoDia.setLayout(new FlowLayout());
//f.setLayout(new GridBagLayout()); //网格包布局
infoDia.setResizable(false);
//fileTa = new TextField("",40);
//infoTa = new TextArea(5,40);
//ipTa = new TextField("",40);
fileBut = new Button("浏览");
sendBut = new Button("发送");
enter = new Button("确定");
ipLab = new Label("发送目的地(192.168.1.*):");
fileLab = new Label("请选择一个文件:");
logLab = new Label("日志");
info = new Label("连接超时,可能是目标不在线");
//infoTa = new TextArea(5,40);
//ipTa = new TextField("",40);
fileDia = new FileDialog(f,"打开",FileDialog.LOAD);
infoDia.add(info);
infoDia.add(enter);
//f.add(fileTa);
//f.add(fileBut);
//f.add(sendBut);
//f.add(infoTa);
GridBagConstraints c=new GridBagConstraints();
c.fill=GridBagConstraints.BOTH; //组
c.insets=new Insets(5,5,5,5); //每个边上都有5个像素的边距
c.gridx=0;c.gridy=0;c.gridwidth=1;c.gridheight=1;
f.add(ipLab,c);
c.gridx=0;c.gridy=1;c.gridwidth=GridBagConstraints.REMAINDER;c.gridheight=1;
f.add(ipTa,c);
c.gridx=0;c.gridy=2;c.gridwidth=1;c.gridheight=1;
f.add(fileLab,c);
c.gridx=0;c.gridy=3;c.gridwidth=1;c.gridheight=1;
f.add(fileTa,c);
c.gridx=1;c.gridy=3;c.gridwidth=1;c.gridheight=1;
f.add(fileBut,c);
c.gridx=2;c.gridy=3;c.gridwidth=1;c.gridheight=1;
f.add(sendBut,c);
c.gridx=0;c.gridy=4;c.gridwidth=1;c.gridheight=1;
f.add(logLab,c);
c.gridx=0;c.gridy=5;c.gridwidth=GridBagConstraints.REMAINDER;c.gridheight=1;
f.add(infoTa,c);
myEvent();
/*ds = new DatagramSocket();
byte[] infobuf = "收到请回答".getBytes();
dp = new DatagramPacket(infobuf,infobuf.length,InetAddress.getByName("192.168.1.255"),10000); //向局域网发出广播,等待回应,以获取对方IP
ds.send(dp);
ds.close();
DatagramSocket dsrece = new DatagramSocket(10000);
byte[] buf = new byte[1024];
DatagramPacket dprece = new DatagramPacket(buf,buf.length);
dsrece.receive(dprece);
ip = dprece.getAddress().getHostAddress();
lst.add(ip);
ipTa.setText(ip);*/
//f.setVisible(true);
}
catch (Exception e)
{
throw new RuntimeException("客户端初始化失败");
}
}
public void myEvent()
{
f.addWindowListener(new WindowAdapter()//关闭窗口
{
public void windowClosing(WindowEvent e)
{
f.setVisible(false);
}
});
infoDia.addWindowListener(new WindowAdapter()//关闭提示信息
{
public void windowClosing(WindowEvent e)
{
infoDia.setVisible(false);
}
});
enter.addActionListener(new ActionListener()//通过回车键关闭窗口
{
public void actionPerformed(ActionEvent e)
{
infoDia.setVisible(false);
}
});
fileBut.addActionListener(new ActionListener()//文件浏览按键事件
{
public void actionPerformed(ActionEvent e)
{
try
{
fileDia.setVisible(true);
String dirPath = fileDia.getDirectory(); //打开文件浏览对话框并获取文件目录
String fileName = fileDia.getFile();//获取文件名
if(dirPath==null || fileName==null)
return ;
fileTa.setText(dirPath+fileName);//将获得的文件名和路径显示在文本框中
file = new File(dirPath,fileName);//创建文件对象.
}
catch (Exception ex2)
{
if(ex2.getStackTrace().toString().contains("NullPointerException"))//判断IP是否输入正确
{
info.setText("请输入一个正确的IP");
infoDia.setVisible(true);
}
}
}
});
sendBut.addActionListener(new ActionListener() //发送文件按键监听事件
{
public void actionPerformed(ActionEvent e)
{
try
{
/*if(ipTa.getText().equals(""))
{
info.setText("请输入一个正确的IP!");
infoDia.setVisible(true);
return;
}*/
ip = ipTa.getText();//获取文本框输入的IP
//ipTa.setText(ip);
Socket s = new Socket();//创建客户端套接
InetSocketAddress addr = new InetSocketAddress(ip,10007);
try
{
s.connect(addr,5000);//连接
}
catch (Exception ex1)
{
if(ex1.getMessage().contains("connect timed out")||ex1.getMessage().contains("Socket is not connected"))
{
infoDia.setVisible(true);
}
if(ex1.getStackTrace().toString().contains("NullPointerException"))
{
info.setText("请输入一个正确的IP");
infoDia.setVisible(true);
}
}
InputStream is = s.getInputStream(); //获取接收端输入流
//byte[] bufip = new byte[256];
//int num1 = is.read(bufip);
//String infoIp = new String(bufip,0,num1);
//System.out.println(infoIp);
BufferedInputStream bufin =
new BufferedInputStream(new FileInputStream(file));//创建文件读取字节流(带缓冲区)
byte[] info = new byte[256];
byte[] b = file.getName().getBytes();
for(int i=0;i<b.length;i++)
{
info[i] = b[i];
}
ByteArrayInputStream bais = new ByteArrayInputStream(info); //字节数组流用于存储文件名
SequenceInputStream sis = new SequenceInputStream(bais,bufin); //将文件名字节流和文件流合并
BufferedOutputStream bufout =
new BufferedOutputStream(s.getOutputStream());
infoTa.append("文件传送中.....\r\n");
int len = 0;
while((len=sis.read())!=-1)
{
bufout.write(len);
}
bufout.flush();
s.shutdownOutput();
//InputStream is = s.getInputStream();
byte[] buf1 = new byte[1023];
int num = is.read(buf1);
String info1 = new String(buf1,0,num);
System.out.println(info1);//打印接收端的反馈信息
infoTa.append(file.getName()+info1+"\r\n");//将信息加入到文本显示区域
bufin.close();//关闭资源
bufout.close();//关闭资源
s.close();
System.out.println("发送端已结束");
}
catch (Exception ex)
{
StackTraceElement[] info1 = ex.getStackTrace();
if(ex.fillInStackTrace().toString().contains("NullPointerException"))
{
info.setText("请输入一个正确的IP");
infoDia.setVisible(true);
}
System.out.println(ex.fillInStackTrace());
System.out.println("----");
if(ex.getMessage().contains("Socket is not connected"))
{
info.setText("无法连接此IP,请检查IP输入是否正确");
infoDia.setVisible(true);
}
///System.out.println(ex.getMessage());
//ex.printStackTrace().toString();
//throw new RuntimeException("111");
}
}
});
}
}
复制代码
作者:
周兴中
时间:
2012-6-28 00:15
分段2
class PicServer implements Runnable //接收端
{
private Frame f;
private TextArea infoTa;
private DatagramSocket ds;
private DatagramPacket dp;
private List lst;
PicServer(Frame f,TextArea infoTa,List lst)
{
this.f = f;
this.infoTa = infoTa;
this.lst = lst;
}
public void init() //初始化界面
{
try
{
/*f = new Frame("ChatDemo");
f.setBounds(300,200,500,300);
f.setLayout(new FlowLayout());
infoTa = new TextArea();
f.add(infoTa);*/
myEvent();
//f.setVisible(true);
/*ds = new DatagramSocket(10000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
ds.close();
String ip = dp.getAddress().getHostAddress();
DatagramSocket dssend = new DatagramSocket();
byte[] infobuf = "收到".getBytes();
DatagramPacket dpsend = new DatagramPacket(infobuf,infobuf.length,InetAddress.getByName(ip),10000);
dssend.send(dpsend);
//lst.add(ip);*/
new Thread(new sendIp()).start();
ServerSocket ss = new ServerSocket(10007); //监听10007端口
while(true) //开启多线程
{
Socket s = ss.accept();
new Thread(new PicThread(s)).start();
}
}
catch (Exception e)
{
throw new RuntimeException("222");
}
}
public void run()
{
try
{
init();
System.out.println("----");
//new PicServer();
//new Thread(new PicClient()).start();
}
catch (Exception e)
{
//e.printStackTrace();
throw new RuntimeException("服务端线程失败");
}
}
public void myEvent()
{
/*f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});*/
}
class PicThread implements Runnable //接收端线程
{
private Socket s;
PicThread(Socket s)
{
this.s = s;
}
public void run()
{
String ip = s.getInetAddress().getHostAddress();//获取客户端地址
int count = 1;
try
{
// InetAddress addr = InetAddress.getLocalHost();
// String ipLoc = addr.getHostAddress();
OutputStream out = s.getOutputStream();
// out.write(ipLoc.getBytes());
System.out.println(ip+"......conected");//显示地址到控制台
infoTa.append(ip+"......conected\r\n");//显示地址到GUI界面文本区域
BufferedInputStream in = new BufferedInputStream(s.getInputStream());
byte[] info = new byte[256];
in.read(info); //读取发送端的文件名
//for(int x = 0 ; x<info.length ; x++)
//System.out.println(info[x]);
String fileName = new String(info).trim();
int dot = fileName.lastIndexOf('.');
String fileName1 = fileName.substring(0,dot);
String exName = fileName.substring(dot);
System.out.println(fileName);
File file = new File("("+ip+")"+fileName);//创建文件对象
while(file.exists())//如果文件已经存在,改名为文件名(count++)
{
file = new File("("+ip+")"+fileName1+"("+(count++)+")"+exName);
}
BufferedOutputStream bufout = new BufferedOutputStream(new FileOutputStream(file));
infoTa.append(ip+".上传的文件"+file.getName()+"接收中....\r\n");
int len = 0;
while((len=in.read())!=-1)
{
bufout.write(len);//接收并写入内存
}
bufout.flush();//写入文件
//OutputStream out = s.getOutputStream();
out.write("上传成功".getBytes());//反馈信息给客户端
infoTa.append(ip+".上传文件"+file.getName()+"成功\r\n");
in.close();//关闭资源
bufout.close();//关闭资源
s.close();//关闭资源
System.out.println("服务端已结束");
}
catch (Exception e)
{
throw new RuntimeException("文件传输线程错误");
}
}
}
}
复制代码
作者:
周兴中
时间:
2012-6-28 00:16
分段3
class FileTransDemo //主线程
{
private Frame f,f1;
private List lst;
private Button getIpBut;
private String ip;
private TextField fileTa,ipTa;
private TextArea infoTa;
private boolean flag1;
private Thread t1;
FileTransDemo()
{
try
{
init();
}
catch (Exception e)
{
e.printStackTrace();
//throw new RuntimeException("777");
}
}
public void init()
{
try
{
f1 = new Frame("LanTransFlieTools");
f1.setBounds(1000,100,200,500);
f1.setLayout(new FlowLayout());
f1.setResizable(false);
lst = new List(20);
getIpBut = new Button("获取对方IP");
f1.add(lst);
f1.add(getIpBut);
//lst.add("Mercury");
//lst.add("Venus");
//lst.add("Earth");
flag1 = false;
myEvent();
f1.setVisible(true);
f = new Frame("局域网文件传输工具(Freemdom)");
f.setBounds(500,200,420,300);
//f.setLayout(new FlowLayout());
f.setLayout(new GridBagLayout()); //网格包布局
f.setResizable(false);
fileTa = new TextField("",40);
fileTa.setEditable(false);
infoTa = new TextArea(5,40);
infoTa.setEditable(false);
ipTa = new TextField("",40);
ipTa.setEditable(false);
new Thread(new PicServer(f,infoTa,lst)).start();
//ipTa.setText(lst.getSelectedItem());
}
catch (Exception e)
{
e.printStackTrace();
//throw new RuntimeException("主程序初始化失败");
}
}
public void myEvent()
{
f1.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
lst.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
ip = lst.getSelectedItem();
System.out.println(ip);
ipTa.setText(ip);
if(!flag1)
{
t1 = new Thread(new PicClient(f,ipTa,fileTa,infoTa,lst,ip));
t1.start();
flag1 = true;
}
System.out.println(t1);
f.setVisible(true);
}
});
getIpBut.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
new Thread(new getIp(lst)).start();
}
});
}
public static void main(String[] args)
{
try
{
new FileTransDemo();
}
catch (Exception e)
{
e.printStackTrace();
//throw new RuntimeException("444");
}
}
}
class getIp implements Runnable //获取在线客户端线程
{
private List lst;
getIp(List lst)
{
this.lst = lst;
}
public void run()
{
try
{
DatagramSocket ds = new DatagramSocket(10000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
ds.close();
String ip = dp.getAddress().getHostAddress();
/*DatagramSocket dssend = new DatagramSocket();
byte[] infobuf = "收到".getBytes();
DatagramPacket dpsend = new DatagramPacket(infobuf,infobuf.length,InetAddress.getByName(ip),10001);
dssend.send(dpsend);
dssend.close();*/
String[] lstIp = lst.getItems() ;
boolean flag = false;
for(int x=0 ; x<lstIp.length; x++)
{
if(ip.equals(lstIp[x]))
flag = true;
}
if(!flag)
lst.add(ip);
}
catch (Exception e)
{
throw new RuntimeException("获取IP线程错误");
}
}
}
class sendIp implements Runnable //发送客户端IP线程.
{
sendIp()
{
}
public void run()
{
try
{
while(true)
{
DatagramSocket ds = new DatagramSocket();
byte[] infobuf = "收到请回答".getBytes();
DatagramPacket dp = new DatagramPacket(infobuf,infobuf.length,InetAddress.getByName("192.168.1.255"),10000);
ds.send(dp);
ds.close();
/*DatagramSocket dsrece = new DatagramSocket(10001);
byte[] buf = new byte[1024];
DatagramPacket dprece = new DatagramPacket(buf,buf.length);
dsrece.receive(dprece);
dsrece.close();*/
//String ip = dprece.getAddress().getHostAddress();
//Thread.sleep(1000);
}
}
catch (Exception e)
{
throw new RuntimeException("发送IP线程错误");
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2