如何通过大量数据传输优化服务器 - 客户端应用程序?

时间:2013-08-19 18:39:52

标签: java image sockets client-server serversocket

我很好奇如何基于套接字或服务器客户端(或任何其他架构)优化应用程序。我是java的新手。我正在尝试基于S-C模型的代码,我觉得在运行此代码时我的机器上有负载。几天前,我记得戴尔技术支持曾经使用一些Java应用程序通过Internet诊断我的PC。只是为了尝试我的技能,并在谷歌的帮助下我编辑了这段代码,并尝试制作类似的应用程序。但我不知道为什么它会带来很大的负担。无论如何,这是我的代码。任何帮助或建议都会很棒。

 Client.Java

import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.*;
import javax.swing.ImageIcon;

public class Client
{
  static BufferedImage bimg;
  static String serverName = "localhost";
  static int port = 6066;
  static Socket client;
  static DataInputStream in;
  static DataOutputStream out ;
  public static void main(String [] args) throws AWTException, UnknownHostException,    IOException
   {

   while(true){
   try
   {
   client = new Socket(serverName, port);

      System.out.println("Connecting to " + serverName
                         + " on port " + port);

     System.out.println("Just connected to "
                  + client.getRemoteSocketAddress());

     in=new DataInputStream(client.getInputStream());
    System.out.println(in.readUTF());
    System.out.println(in.readUTF());

     out =
                   new DataOutputStream(client.getOutputStream());

     out.writeUTF("Hello from "
                  + client.getLocalSocketAddress());
     out.writeUTF("client: hello to server");

     bimg = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));

     ImageIO.write(bimg,"JPG",client.getOutputStream());
     System.out.println("Image sent!!!!");
     client.close();
  out.flush();
  in.close();
  out.close();
  }catch(IOException e)
  {
     e.printStackTrace();
   }}
   }
   }

Server.java

     public class Server extends Thread {

     private ServerSocket serverSocket;
     Socket server;
     JFrame VF;
     static ImagePanel im;
     static BufferedImage bp;

     public Server(int port) throws IOException, SQLException, ClassNotFoundException,      Exception {
     serverSocket = new ServerSocket(port);
     serverSocket.setSoTimeout(180000);
    VF = new JFrame("Video output");
    im = new ImagePanel();
    im.setImage("screenshot.png");

    im.setroundcorners(true, 10);

    im.setImagePanelBounds(20, 20, 500, 500);
    VF.pack();

    VF.setLayout(new BorderLayout());
    VF.add(im, BorderLayout.CENTER);
    VF.setSize(800, 800);
    VF.setLocation(10, 10);
    VF.setVisible(true);
    //startVideo();
    VF.addComponentListener(new ComponentListener() {
        @Override
        public void componentResized(ComponentEvent ce) {
            im.setImagePanelBounds(0, 0, VF.getWidth(), VF.getHeight());
            //        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void componentMoved(ComponentEvent ce) {
            //      throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void componentShown(ComponentEvent ce) {
            //    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void componentHidden(ComponentEvent ce) {
            //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });
    //
}

public void run() {
    while (true) {
        try {
            server = serverSocket.accept();
            DataInputStream din = new DataInputStream(server.getInputStream());
            DataOutputStream dout = new DataOutputStream(server.getOutputStream());

            dout.writeUTF("server: -i am greeting server");
            dout.writeUTF("server:- hi! hello client");

            System.out.println(din.readUTF());
            System.out.println(din.readUTF());

            bp = ImageIO.read(ImageIO.createImageInputStream(server.getInputStream()));

            System.out.println("Image received!!!!");
            //lblimg.setIcon(img);
        } catch (SocketTimeoutException st) {
            System.out.println("Socket timed out!");
            break;
        } catch (IOException e) {
            e.printStackTrace();
            break;
        } catch (Exception ex) {
            System.out.println(ex);
        }

        //here in new


        //   throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        int i = 0;

        {

            im.setImage(bp);
            im.repaint();
            VF.repaint();
            VF.revalidate();

        }

    }



    //here is end
}

  public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException, Exception {
    //int port = Integer.parseInt(args[0]);
    Thread t = new Server(6066);
    t.start();
}
}

ImagePanel.java

class ImagePanel extends JPanel {

int g_h = 10, g_w = 10;
int width = 100;
int height = 100;
int cornerradius;
Image castle;
Dimension size;
protected int x1, y1;
Color c1 = new Color(255, 0, 0);
Rectangle rec;
boolean b = false;
boolean imboo = false;
boolean roundb = false;
boolean ovalb = false;
protected int strokeSize = 1;
protected Color shadowColor = Color.BLACK;
boolean shadowed = false;

public ImagePanel() {
    //super();
    setOpaque(false);
    setLayout(null);
    //System.out.println("it executed");

  //this.paint(g);
   }

public ImagePanel(int x, int y) {
    this.height = this.getParent().getHeight();
    setSize(x, y);
}

public void setSize(int x, int y) {
    this.width = x;
    this.height = y;
}

public int getheight() {

    return height;
}

public int getwidth() {

    return width;
}

public void setImagePanelBounds(int x, int y, int width, int height) {
    x1 = x;
    y1 = y;
    this.width = width;
    this.height = height;
    //System.out.println("6it executed");
}

public void setroundcorners(boolean b, int i) {
    roundb = b;
    cornerradius = i;
    ////System.out.println("5it executed");

}

public void setoval(boolean b, int i) {
    roundb = b;
    cornerradius = i;
    ////System.out.println("5it executed");

}

public void setImage(BufferedImage bi) {
    imboo = true;
    size = new Dimension();

    castle = (Image) bi;
    size.width = castle.getWidth(null);
    size.height = castle.getHeight(null);
    setPreferredSize(size);
    //System.out.println("4it executed");
}

public void setImage(String s) {
    imboo = true;
    size = new Dimension();
    castle = new ImageIcon(s).getImage();
    size.width = castle.getWidth(null);
    size.height = castle.getHeight(null);
    setPreferredSize(size);
    //System.out.println("4it executed");
}

//public void addc(Component c){
//  this.add(c);
   public void paint(Graphics gh) { ////System.out.println("it executed p");
    {
        int x = this.getWidth();
        int j = 20, a = 20;
  //BufferedImage output = new BufferedImage(x, this.getheight(),BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = (Graphics2D) gh.create();
        // Graphics2D g2= output.createGraphics();
        // super.paint(g);// why it was here ???
        {
            g2.setColor(Color.WHITE);
            g2.setComposite(AlphaComposite.Src);
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setComposite(AlphaComposite.SrcAtop);
            rec = new Rectangle(x1, y1, width, height);
        //Start of If-else


            if (roundb) {
                g2.setClip(new RoundRectangle2D.Float((int) rec.getX(), (int) rec.getY(), (int) rec.getWidth(), (int) rec.getHeight(), cornerradius, cornerradius));
                //System.out.println("it executed");
            }
            if (ovalb) {
                g2.setClip(new Ellipse2D.Float((int) rec.getX(), (int) rec.getY(), cornerradius, cornerradius));
                //System.out.println("it executed");
            }

            // End of If-Else
            // Image condition  Starts
            if (imboo) {
                g2.drawImage(castle, (int) rec.getX(), (int) rec.getY(), (int) rec.getWidth(), (int) rec.getHeight(), null);
                //g.drawImage(castle, (int)rec.getX(),(int)rec.getY(),  null);

            }
            // Image condition  Ends
            g2.setColor(Color.BLUE);
        }




        g2.dispose();
    }

}

public int getImageHeight() {
    return (int) rec.getHeight();

}

public int getImageWidth() {
    return (int) rec.getWidth();

}

 }

我知道客户端每次都在创建新实例。

client = new Socket(serverName, port);

那么最后两个问题,在Client.java中执行每个循环如何从一个端口发送数据而不打开新端口?如何检查我的代码是否已完全优化? (比如哪个元素或哪个循环花费了多少内存) 提前致谢 !!!!! (道歉有时我的好奇心和对知识的兴奋太高,以至于很难提出问题,因为很多事情在我的脑海中浮现。:-) LOLz)

1 个答案:

答案 0 :(得分:0)

k,我明白了(仍然怀疑它)。 imagePanel在执行时吃了太多内存。 通过@MadProgrammer TmagePaneExample使用ImagePaneExample解决了这个问题。加上我认为我不需要客户端的特定端口,如果客户端运行的应用程序太多,它只会增加失败的几率。

无论如何,谢谢!!!