A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

本帖最后由 周兴中 于 2012-6-28 00:17 编辑

各功能使用正常,就是CPU使用率偏高,请大侠指点,该如何优化.
由于代码冗长,分段成3段
以下为分段1:
  1. package filetransdemo;
  2. import java.io.*;
  3. import java.net.*;
  4. import java.awt.*;
  5. import java.awt.event.*;
  6. *class PicClient implements Runnable //客户端
  7. {
  8. private Frame f;
  9. private TextArea infoTa;
  10. private TextField ipTa,fileTa;
  11. private Button fileBut,sendBut,enter;
  12. private FileDialog fileDia;
  13. private File file;
  14. private Label ipLab,fileLab,logLab,info;
  15. private Dialog infoDia;
  16. private DatagramSocket ds;
  17. private DatagramPacket dp;
  18. private List lst;
  19. private String ip;

  20. PicClient(Frame f,TextField ipTa,TextField fileTa,TextArea infoTa,List lst,String ip)
  21. {
  22. this.f = f;
  23. this.ipTa = ipTa;
  24. this.fileTa = fileTa;
  25. this.infoTa = infoTa;
  26. this.lst =lst;
  27. this.ip = ip;

  28. }

  29. public void run()
  30. {
  31. try
  32. {
  33. init();
  34. }
  35. catch (Exception e)
  36. {
  37. throw new RuntimeException("客户端初始化失败");
  38. }

  39. }
  40. public void init() //客户端初始化
  41. {
  42. try
  43. {


  44. infoDia = new Dialog(f,"提示信息",true);
  45. infoDia.setBounds(600,300,300,80);
  46. infoDia.setLayout(new FlowLayout());
  47. //f.setLayout(new GridBagLayout()); //网格包布局
  48. infoDia.setResizable(false);



  49. //fileTa = new TextField("",40);
  50. //infoTa = new TextArea(5,40);
  51. //ipTa = new TextField("",40);

  52. fileBut = new Button("浏览");

  53. sendBut = new Button("发送");
  54. enter = new Button("确定");

  55. ipLab = new Label("发送目的地(192.168.1.*):");
  56. fileLab = new Label("请选择一个文件:");
  57. logLab = new Label("日志");
  58. info = new Label("连接超时,可能是目标不在线");

  59. //infoTa = new TextArea(5,40);
  60. //ipTa = new TextField("",40);

  61. fileDia = new FileDialog(f,"打开",FileDialog.LOAD);

  62. infoDia.add(info);
  63. infoDia.add(enter);


  64. //f.add(fileTa);
  65. //f.add(fileBut);
  66. //f.add(sendBut);
  67. //f.add(infoTa);

  68. GridBagConstraints c=new GridBagConstraints();
  69. c.fill=GridBagConstraints.BOTH; //组
  70. c.insets=new Insets(5,5,5,5); //每个边上都有5个像素的边距
  71. c.gridx=0;c.gridy=0;c.gridwidth=1;c.gridheight=1;
  72. f.add(ipLab,c);
  73. c.gridx=0;c.gridy=1;c.gridwidth=GridBagConstraints.REMAINDER;c.gridheight=1;
  74. f.add(ipTa,c);
  75. c.gridx=0;c.gridy=2;c.gridwidth=1;c.gridheight=1;
  76. f.add(fileLab,c);
  77. c.gridx=0;c.gridy=3;c.gridwidth=1;c.gridheight=1;
  78. f.add(fileTa,c);
  79. c.gridx=1;c.gridy=3;c.gridwidth=1;c.gridheight=1;
  80. f.add(fileBut,c);
  81. c.gridx=2;c.gridy=3;c.gridwidth=1;c.gridheight=1;
  82. f.add(sendBut,c);
  83. c.gridx=0;c.gridy=4;c.gridwidth=1;c.gridheight=1;
  84. f.add(logLab,c);
  85. c.gridx=0;c.gridy=5;c.gridwidth=GridBagConstraints.REMAINDER;c.gridheight=1;
  86. f.add(infoTa,c);

  87. myEvent();

  88. /*ds = new DatagramSocket();
  89. byte[] infobuf = "收到请回答".getBytes();
  90. dp = new DatagramPacket(infobuf,infobuf.length,InetAddress.getByName("192.168.1.255"),10000); //向局域网发出广播,等待回应,以获取对方IP
  91. ds.send(dp);
  92. ds.close();

  93. DatagramSocket dsrece = new DatagramSocket(10000);
  94. byte[] buf = new byte[1024];
  95. DatagramPacket dprece = new DatagramPacket(buf,buf.length);
  96. dsrece.receive(dprece);

  97. ip = dprece.getAddress().getHostAddress();

  98. lst.add(ip);
  99. ipTa.setText(ip);*/






  100. //f.setVisible(true);
  101. }
  102. catch (Exception e)
  103. {
  104. throw new RuntimeException("客户端初始化失败");
  105. }





  106. }

  107. public void myEvent()
  108. {
  109. f.addWindowListener(new WindowAdapter()//关闭窗口
  110. {
  111. public void windowClosing(WindowEvent e)
  112. {
  113. f.setVisible(false);
  114. }
  115. });

  116. infoDia.addWindowListener(new WindowAdapter()//关闭提示信息
  117. {
  118. public void windowClosing(WindowEvent e)
  119. {
  120. infoDia.setVisible(false);
  121. }
  122. });

  123. enter.addActionListener(new ActionListener()//通过回车键关闭窗口
  124. {
  125. public void actionPerformed(ActionEvent e)
  126. {
  127. infoDia.setVisible(false);
  128. }
  129. });

  130. fileBut.addActionListener(new ActionListener()//文件浏览按键事件
  131. {
  132. public void actionPerformed(ActionEvent e)
  133. {
  134. try
  135. {


  136. fileDia.setVisible(true);
  137. String dirPath = fileDia.getDirectory(); //打开文件浏览对话框并获取文件目录
  138. String fileName = fileDia.getFile();//获取文件名
  139. if(dirPath==null || fileName==null)
  140. return ;
  141. fileTa.setText(dirPath+fileName);//将获得的文件名和路径显示在文本框中
  142. file = new File(dirPath,fileName);//创建文件对象.
  143. }
  144. catch (Exception ex2)
  145. {
  146. if(ex2.getStackTrace().toString().contains("NullPointerException"))//判断IP是否输入正确
  147. {

  148. info.setText("请输入一个正确的IP");
  149. infoDia.setVisible(true);
  150. }
  151. }



  152. }
  153. });

  154. sendBut.addActionListener(new ActionListener() //发送文件按键监听事件
  155. {
  156. public void actionPerformed(ActionEvent e)
  157. {
  158. try
  159. {
  160. /*if(ipTa.getText().equals(""))
  161. {
  162. info.setText("请输入一个正确的IP!");
  163. infoDia.setVisible(true);
  164. return;
  165. }*/
  166. ip = ipTa.getText();//获取文本框输入的IP

  167. //ipTa.setText(ip);
  168. Socket s = new Socket();//创建客户端套接
  169. InetSocketAddress addr = new InetSocketAddress(ip,10007);
  170. try
  171. {
  172. s.connect(addr,5000);//连接
  173. }
  174. catch (Exception ex1)
  175. {
  176. if(ex1.getMessage().contains("connect timed out")||ex1.getMessage().contains("Socket is not connected"))
  177. {
  178. infoDia.setVisible(true);

  179. }
  180. if(ex1.getStackTrace().toString().contains("NullPointerException"))
  181. {

  182. info.setText("请输入一个正确的IP");
  183. infoDia.setVisible(true);

  184. }


  185. }




  186. InputStream is = s.getInputStream(); //获取接收端输入流

  187. //byte[] bufip = new byte[256];

  188. //int num1 = is.read(bufip);
  189. //String infoIp = new String(bufip,0,num1);
  190. //System.out.println(infoIp);
  191. BufferedInputStream bufin =
  192. new BufferedInputStream(new FileInputStream(file));//创建文件读取字节流(带缓冲区)

  193. byte[] info = new byte[256];
  194. byte[] b = file.getName().getBytes();
  195. for(int i=0;i<b.length;i++)
  196. {
  197. info[i] = b[i];
  198. }
  199. ByteArrayInputStream bais = new ByteArrayInputStream(info); //字节数组流用于存储文件名

  200. SequenceInputStream sis = new SequenceInputStream(bais,bufin); //将文件名字节流和文件流合并



  201. BufferedOutputStream bufout =
  202. new BufferedOutputStream(s.getOutputStream());
  203. infoTa.append("文件传送中.....\r\n");
  204. int len = 0;
  205. while((len=sis.read())!=-1)
  206. {
  207. bufout.write(len);

  208. }

  209. bufout.flush();

  210. s.shutdownOutput();



  211. //InputStream is = s.getInputStream();

  212. byte[] buf1 = new byte[1023];

  213. int num = is.read(buf1);

  214. String info1 = new String(buf1,0,num);
  215. System.out.println(info1);//打印接收端的反馈信息

  216. infoTa.append(file.getName()+info1+"\r\n");//将信息加入到文本显示区域


  217. bufin.close();//关闭资源


  218. bufout.close();//关闭资源

  219. s.close();

  220. System.out.println("发送端已结束");
  221. }
  222. catch (Exception ex)
  223. {
  224. StackTraceElement[] info1 = ex.getStackTrace();
  225. if(ex.fillInStackTrace().toString().contains("NullPointerException"))
  226. {
  227. info.setText("请输入一个正确的IP");
  228. infoDia.setVisible(true);
  229. }
  230. System.out.println(ex.fillInStackTrace());
  231. System.out.println("----");
  232. if(ex.getMessage().contains("Socket is not connected"))
  233. {
  234. info.setText("无法连接此IP,请检查IP输入是否正确");
  235. infoDia.setVisible(true);
  236. }
  237. ///System.out.println(ex.getMessage());
  238. //ex.printStackTrace().toString();
  239. //throw new RuntimeException("111");
  240. }


  241. }
  242. });
  243. }



  244. }
复制代码

2 个回复

倒序浏览
分段2
  1. class  PicServer implements Runnable //接收端
  2. {
  3.         private Frame f;
  4.         private TextArea infoTa;
  5.         private DatagramSocket ds;
  6.         private DatagramPacket dp;
  7.         private List lst;

  8.         PicServer(Frame f,TextArea infoTa,List lst)
  9.         {
  10.                 this.f = f;
  11.                 this.infoTa = infoTa;       
  12.                 this.lst = lst;
  13.         }

  14.         public void init() //初始化界面
  15.         {
  16.                 try
  17.                 {
  18.                         /*f = new Frame("ChatDemo");
  19.                 f.setBounds(300,200,500,300);
  20.                 f.setLayout(new FlowLayout());

  21.                 infoTa = new TextArea();

  22.                 f.add(infoTa);*/

  23.                 myEvent();

  24.                 //f.setVisible(true);

  25.                 /*ds = new DatagramSocket(10000);
  26.                 byte[] buf = new byte[1024];
  27.                 DatagramPacket dp = new DatagramPacket(buf,buf.length);
  28.                 ds.receive(dp);
  29.                 ds.close();


  30.                 String ip = dp.getAddress().getHostAddress();
  31.                 DatagramSocket dssend = new DatagramSocket();
  32.                 byte[] infobuf = "收到".getBytes();
  33.                 DatagramPacket dpsend = new DatagramPacket(infobuf,infobuf.length,InetAddress.getByName(ip),10000);
  34.                 dssend.send(dpsend);
  35.                 //lst.add(ip);*/
  36.                 new Thread(new sendIp()).start();


  37.                 ServerSocket ss = new ServerSocket(10007); //监听10007端口

  38.                 while(true) //开启多线程
  39.                 {
  40.                         Socket s = ss.accept();

  41.                         new Thread(new PicThread(s)).start();
  42.                        
  43.                        
  44.                 }
  45.                 }
  46.                 catch (Exception e)
  47.                 {
  48.                         throw new RuntimeException("222");
  49.                 }
  50.                


  51.         }

  52.         public void run()
  53.         {
  54.                 try
  55.                 {
  56.                         init();
  57.                         System.out.println("----");
  58.                         //new PicServer();
  59.                         //new Thread(new PicClient()).start();
  60.                 }
  61.                 catch (Exception e)
  62.                 {
  63.                         //e.printStackTrace();
  64.                         throw new RuntimeException("服务端线程失败");
  65.                 }
  66.                
  67.         }

  68.         public void myEvent()
  69.         {
  70.                 /*f.addWindowListener(new WindowAdapter()
  71.                 {
  72.                         public void windowClosing(WindowEvent e)
  73.                         {
  74.                                 System.exit(0);
  75.                         }
  76.                 });*/
  77.         }

  78.         class PicThread implements Runnable //接收端线程
  79. {
  80.         private Socket s;
  81.         PicThread(Socket s)
  82.         {
  83.                 this.s = s;
  84.         }

  85.         public void run()
  86.         {
  87.                 String ip = s.getInetAddress().getHostAddress();//获取客户端地址
  88.                 int count = 1;
  89.                 try
  90.                 {
  91.                        
  92.                 //        InetAddress addr = InetAddress.getLocalHost();
  93.                 //        String ipLoc = addr.getHostAddress();
  94.                         OutputStream out = s.getOutputStream();

  95.                 //        out.write(ipLoc.getBytes());

  96.                         System.out.println(ip+"......conected");//显示地址到控制台
  97.                         infoTa.append(ip+"......conected\r\n");//显示地址到GUI界面文本区域
  98.                        
  99.                         BufferedInputStream in = new BufferedInputStream(s.getInputStream());

  100.                         byte[] info = new byte[256];         
  101.                         in.read(info); //读取发送端的文件名
  102.                         //for(int x = 0 ; x<info.length ; x++)
  103.                                 //System.out.println(info[x]);
  104.                     
  105.                         String fileName = new String(info).trim();
  106.                         int dot = fileName.lastIndexOf('.');

  107.                         String fileName1 = fileName.substring(0,dot);

  108.                         String exName = fileName.substring(dot);

  109.                        
  110.                         System.out.println(fileName);

  111.                        
  112.                         File file = new File("("+ip+")"+fileName);//创建文件对象

  113.                         while(file.exists())//如果文件已经存在,改名为文件名(count++)
  114.                         {
  115.                                 file = new File("("+ip+")"+fileName1+"("+(count++)+")"+exName);
  116.                         }

  117.                         BufferedOutputStream bufout = new BufferedOutputStream(new FileOutputStream(file));
  118.                         infoTa.append(ip+".上传的文件"+file.getName()+"接收中....\r\n");
  119.                         int len = 0;
  120.                         while((len=in.read())!=-1)
  121.                         {
  122.                                 bufout.write(len);//接收并写入内存
  123.                                
  124.                         }
  125.                         bufout.flush();//写入文件

  126.                         //OutputStream out = s.getOutputStream();

  127.                         out.write("上传成功".getBytes());//反馈信息给客户端

  128.                         infoTa.append(ip+".上传文件"+file.getName()+"成功\r\n");

  129.                         in.close();//关闭资源

  130.                         bufout.close();//关闭资源

  131.                         s.close();//关闭资源

  132.                         System.out.println("服务端已结束");
  133.                 }
  134.                 catch (Exception e)
  135.                 {
  136.                         throw new RuntimeException("文件传输线程错误");
  137.                 }
  138.                     
  139.         }
  140. }
  141.        
  142. }
复制代码
回复 使用道具 举报
分段3
  1. class FileTransDemo //主线程
  2. {
  3.         private Frame f,f1;
  4.         private List lst;
  5.         private Button getIpBut;
  6.         private String ip;
  7.         private TextField fileTa,ipTa;
  8.         private TextArea infoTa;
  9.         private boolean flag1;
  10.         private Thread t1;

  11.         FileTransDemo()
  12.         {
  13.                 try
  14.                 {
  15.                         init();
  16.                 }
  17.                 catch (Exception e)
  18.                 {
  19.                         e.printStackTrace();
  20.                         //throw new RuntimeException("777");

  21.                 }
  22.                
  23.         }

  24.         public void init()
  25.         {
  26.                 try
  27.                 {
  28.                         f1 = new Frame("LanTransFlieTools");
  29.                         f1.setBounds(1000,100,200,500);
  30.                         f1.setLayout(new FlowLayout());
  31.                         f1.setResizable(false);

  32.                         lst = new List(20);

  33.                         getIpBut = new Button("获取对方IP");

  34.                         f1.add(lst);
  35.                         f1.add(getIpBut);
  36.                         //lst.add("Mercury");
  37.                         //lst.add("Venus");
  38.                         //lst.add("Earth");
  39.                        
  40.                         flag1 = false;

  41.                         myEvent();
  42.                        
  43.                         f1.setVisible(true);
  44.                         f = new Frame("局域网文件传输工具(Freemdom)");
  45.                         f.setBounds(500,200,420,300);
  46.                         //f.setLayout(new FlowLayout());
  47.                         f.setLayout(new GridBagLayout()); //网格包布局
  48.                         f.setResizable(false);
  49.                          fileTa = new TextField("",40);
  50.                         fileTa.setEditable(false);
  51.                         infoTa = new TextArea(5,40);
  52.                         infoTa.setEditable(false);
  53.                         ipTa = new TextField("",40);
  54.                         ipTa.setEditable(false);
  55.                        
  56.                        
  57.                         new Thread(new PicServer(f,infoTa,lst)).start();
  58.                        

  59.                         //ipTa.setText(lst.getSelectedItem());
  60.                        
  61.                 }
  62.                 catch (Exception e)
  63.                 {
  64.                         e.printStackTrace();
  65.                         //throw new RuntimeException("主程序初始化失败");
  66.                 }
  67.        

  68.         }
  69.         public void myEvent()
  70.         {
  71.                 f1.addWindowListener(new WindowAdapter()
  72.                 {
  73.                         public void windowClosing(WindowEvent e)
  74.                         {
  75.                                 System.exit(0);
  76.                         }
  77.                 });

  78.                 lst.addActionListener(new ActionListener()
  79.                 {
  80.                         public void actionPerformed(ActionEvent e)
  81.                         {
  82.                                
  83.                                        
  84.                                        
  85.                                        
  86.                                         ip = lst.getSelectedItem();
  87.                                         System.out.println(ip);
  88.                                         ipTa.setText(ip);
  89.                                         if(!flag1)
  90.                                         {
  91.                                                 t1 = new Thread(new PicClient(f,ipTa,fileTa,infoTa,lst,ip));
  92.                                                 t1.start();
  93.                                                 flag1 = true;
  94.                                         }
  95.                                         System.out.println(t1);

  96.                                         f.setVisible(true);


  97.                                
  98.                         }
  99.                 });

  100.                 getIpBut.addActionListener(new ActionListener()
  101.                 {
  102.                         public void actionPerformed(ActionEvent e)
  103.                         {
  104.                                
  105.                                        
  106.                                        
  107.                                         new Thread(new getIp(lst)).start();
  108.                                
  109.                                


  110.                                
  111.                         }
  112.                 });
  113.         }

  114.         public static void main(String[] args)
  115.         {
  116.                 try
  117.                 {
  118.                         new FileTransDemo();
  119.                 }
  120.                 catch (Exception e)
  121.                 {
  122.                         e.printStackTrace();
  123.                         //throw new RuntimeException("444");
  124.                 }
  125.                
  126.         }
  127. }

  128. class getIp implements Runnable //获取在线客户端线程
  129. {
  130.         private List lst;
  131.        

  132.         getIp(List lst)
  133.         {
  134.                 this.lst = lst;

  135.                
  136.         }
  137.        
  138.         public void run()
  139.         {
  140.                 try
  141.                 {
  142.                                 DatagramSocket ds = new DatagramSocket(10000);
  143.                                 byte[] buf = new byte[1024];
  144.                                 DatagramPacket dp = new DatagramPacket(buf,buf.length);
  145.                                 ds.receive(dp);
  146.                                 ds.close();
  147.                                
  148.                                 String ip = dp.getAddress().getHostAddress();
  149.                                
  150.                                 /*DatagramSocket dssend = new DatagramSocket();
  151.                                 byte[] infobuf = "收到".getBytes();
  152.                                 DatagramPacket dpsend = new DatagramPacket(infobuf,infobuf.length,InetAddress.getByName(ip),10001);
  153.                                 dssend.send(dpsend);
  154.                                
  155.                                 dssend.close();*/
  156.                         String[] lstIp = lst.getItems() ;

  157.                         boolean flag = false;
  158.                         for(int x=0 ; x<lstIp.length; x++)
  159.                         {
  160.                                 if(ip.equals(lstIp[x]))
  161.                                 flag = true;
  162.                         }
  163.                         if(!flag)
  164.                         lst.add(ip);

  165.                        
  166.                        
  167.                 }
  168.                 catch (Exception e)
  169.                 {
  170.                         throw new RuntimeException("获取IP线程错误");
  171.                 }
  172.                
  173.         }

  174. }

  175. class sendIp implements Runnable //发送客户端IP线程.
  176. {
  177.         sendIp()
  178.         {
  179.                
  180.         }

  181.         public void run()
  182.         {
  183.                 try
  184.                 {
  185.                         while(true)
  186.                         {
  187.                                
  188.                                 DatagramSocket ds = new DatagramSocket();
  189.                                 byte[] infobuf = "收到请回答".getBytes();
  190.                                 DatagramPacket dp = new DatagramPacket(infobuf,infobuf.length,InetAddress.getByName("192.168.1.255"),10000);
  191.                                 ds.send(dp);
  192.                                 ds.close();
  193.                                
  194.                                
  195.                                 /*DatagramSocket dsrece = new DatagramSocket(10001);
  196.                                 byte[] buf = new byte[1024];
  197.                                 DatagramPacket dprece = new DatagramPacket(buf,buf.length);
  198.                                 dsrece.receive(dprece);
  199.                                
  200.                                 dsrece.close();*/

  201.                                 //String ip = dprece.getAddress().getHostAddress();
  202.                                
  203.                                 //Thread.sleep(1000);
  204.                         }
  205.                 }
  206.                 catch (Exception e)
  207.                 {
  208.                         throw new RuntimeException("发送IP线程错误");
  209.                 }
  210.                
  211.         }
  212. }
复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马