繁体   English   中英

如何在Java中将多种方法编码到一个客户端/服务器应用程序中

[英]How to code multiple methods into one client/server application in java

我有一个尝试使用Java编写的客户端/服务器应用程序,该应用程序应该能够执行许多功能,并且每次服务器都应该响应。 即,客户端具有GUI,而服务器是控制台应用程序。 服务器应该能够列出我指定的所有文本文档(将由FileInputStream读取),显示其内容并将修改后的内容保存到同一文件中。

我的问题是,我希望能够将这三个操作分解为客户端的方法,并让服务器响应。 客户端关闭窗口的那一刻,连接必须关闭。 我在下面插入了代码以说明我要执行的操作:

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class Client extends JFrame
{
    //<variables> machine generated (do not edit)
    JScrollPane jScrollPane2;
    JList jList1;
    JScrollPane jScrollPane1;
    JList jList2;
    JButton btnLoad;
    JPanel jPanel1;
    JLabel jLabel2;
    JTextField jTextField1;
    JButton btnSave;
    JLabel jLabel1;
    //</variables> machine generated (do not edit)

    public  ObjectOutputStream output;
    public  ObjectInputStream input;
    String message = "";
    String filenames = "";
    public  Socket client;

    public DefaultListModel lm = new DefaultListModel();


    public Client()
    {
        Container cp = getContentPane();
        cp.setLayout(new BorderLayout());
        createJPanel1();

        runClient();

        this.addWindowListener(
            new WindowAdapter() 
            {
                public void windowClosing(WindowEvent e) 
                {
                    try
                    {
                        System.out.println("Operation closing");
                        output.close();
                          input.close();
                          client.close();
                          System.exit(0);
                      }
                      catch (IOException classNotFoundException )
                      {
                         System.out.println( "Couldn't close" );
                      }
                  }
              });
        //add your own code here
        cp.add(jPanel1);
        pack();
    }

    public void runClient()
    {
       try
       {
            connectToServer();
            getStreams();
            getData();
            ButtonEvent();
         }
         catch (IOException classNotFoundException )
         {
             System.out.println("Couldn't run the client");
         }
   }
   public void connectToServer() throws IOException
   {
      System.out.println( "Attempting connection\n" );
      client = new Socket(InetAddress.getLocalHost(), 5001 );
      System.out.println( "Connected to: " + client.getInetAddress().getHostName() );
   }
   private void getStreams() throws IOException
   {
      output = new ObjectOutputStream(client.getOutputStream());
      output.flush();
      input = new ObjectInputStream(client.getInputStream() );
      System.out.println( "Got I/O streams" );

   }
   private void getData() throws IOException
   {
       try
           {     
              filenames = (String)input.readObject();
              lm.addElement(filenames + "\n\r");
              jList1.setModel(lm);
         }
         catch (IOException err)
        {
            System.out.println("Error: " + err.getMessage());
        }
        catch (ClassNotFoundException classNotFoundException)
        {
            System.out.println( "Something went wrong" + classNotFoundException.getMessage() );
        }          
   }
   public void ButtonEvent() throws IOException
   {
       try
       {
           btnLoad.addActionListener(new ActionListener()
                 {
                      public void actionPerformed(ActionEvent ev)
                    {
                        try
                        {
                            String command = btnLoad.getText().toString();
                            output.writeObject(command);
                            output.flush();
                        }
                        catch(IOException ee)
                        {
                            ee.printStackTrace();
                        }
                    }
                });
       }
       catch (Exception error)
       {
           System.out.println("Error on button"  + error.getMessage());
       }         
   }
    public static void main(String []args)
    {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {System.err.println("Could not set look and feel");}
        Client startFrame = new Client();
        startFrame.setVisible(true);
    }
    // <design0>
    //this method is computer generated (do not edit)
    public JPanel createJPanel1()
    {
        jPanel1 = new JPanel();
        SpringLayout jPanel1Layout = new SpringLayout();
        jPanel1.setLayout(jPanel1Layout);
        SpringLayout.Constraints jPanel1Cons = jPanel1Layout.getConstraints(jPanel1);
        jPanel1Cons.setConstraint("East",Spring.constant(310,310,1530));
        jPanel1Cons.setConstraint("South",Spring.constant(310,510,1530));
        Spring jPanel1East = jPanel1Layout.getConstraint("East",jPanel1);
        Spring jPanel1South = jPanel1Layout.getConstraint("South",jPanel1);
        Spring jPanel1West = jPanel1Layout.getConstraint("West",jPanel1);
        Spring jPanel1North = jPanel1Layout.getConstraint("North",jPanel1);
        jPanel1.setName("jPanel1");
        jLabel1 = new JLabel();
        jLabel1.setFont(new Font("Tahoma",Font.BOLD,15));
        jLabel1.setName("jLabel1");
        jLabel1.setText("Filename:");
        SpringLayout.Constraints jLabel1Cons = jPanel1Layout.getConstraints(jLabel1);
        jLabel1Cons.setConstraint("East", Spring.constant(105));
        jLabel1Cons.setConstraint("West", Spring.constant(15));
        jLabel1Cons.setConstraint("South", Spring.constant(55));
        jLabel1Cons.setConstraint("North", Spring.constant(25));
        jPanel1.add(jLabel1);
        jTextField1 = new JTextField();
        jTextField1.setName("jTextField1");
        SpringLayout.Constraints jTextField1Cons = jPanel1Layout.getConstraints(jTextField1);
        jTextField1Cons.setConstraint("East", Spring.constant(295));
        jTextField1Cons.setConstraint("West", Spring.constant(110));
        jTextField1Cons.setConstraint("South", Spring.constant(55));
        jTextField1Cons.setConstraint("North", Spring.constant(25));
        jPanel1.add(jTextField1);
        jScrollPane1 = new JScrollPane();
        jScrollPane1.setName("jScrollPane1");
        SpringLayout.Constraints jScrollPane1Cons = jPanel1Layout.getConstraints(jScrollPane1);
        jScrollPane1Cons.setConstraint("East", Spring.constant(295));
        jScrollPane1Cons.setConstraint("West", Spring.constant(10));
        jScrollPane1Cons.setConstraint("South", Spring.constant(245));
        jScrollPane1Cons.setConstraint("North", Spring.constant(70));
        jPanel1.add(jScrollPane1);
        jList1 = new JList();
        jList1.setName("jList1");
        jScrollPane1.setViewportView(jList1);
        btnLoad = new JButton();
        btnLoad.setName("btnLoad");
        btnLoad.setText("Load");
        SpringLayout.Constraints btnLoadCons = jPanel1Layout.getConstraints(btnLoad);
        btnLoadCons.setConstraint("East", Spring.constant(125));
        btnLoadCons.setConstraint("West", Spring.constant(35));
        btnLoadCons.setConstraint("South", Spring.constant(285));
        btnLoadCons.setConstraint("North", Spring.constant(255));
        jPanel1.add(btnLoad);
        btnSave = new JButton();
        btnSave.setName("btnSave");
        btnSave.setText("Save");
        SpringLayout.Constraints btnSaveCons = jPanel1Layout.getConstraints(btnSave);
        btnSaveCons.setConstraint("East", Spring.constant(240));
        btnSaveCons.setConstraint("West", Spring.constant(150));
        btnSaveCons.setConstraint("South", Spring.constant(285));
        btnSaveCons.setConstraint("North", Spring.constant(255));
        jPanel1.add(btnSave);
        jScrollPane2 = new JScrollPane();
        jScrollPane2.setName("jScrollPane2");
        SpringLayout.Constraints jScrollPane2Cons = jPanel1Layout.getConstraints(jScrollPane2);
        jScrollPane2Cons.setConstraint("East", Spring.constant(300));
        jScrollPane2Cons.setConstraint("West", Spring.constant(10));
        jScrollPane2Cons.setConstraint("South", Spring.constant(495));
        jScrollPane2Cons.setConstraint("North", Spring.constant(345));
        jPanel1.add(jScrollPane2);
        jList2 = new JList();
        jList2.setName("jList2");
        jScrollPane2.setViewportView(jList2);
        jLabel2 = new JLabel();
        jLabel2.setName("jLabel2");
        jLabel2.setText("File Contents:");
        SpringLayout.Constraints jLabel2Cons = jPanel1Layout.getConstraints(jLabel2);
        jLabel2Cons.setConstraint("East", Spring.constant(190));
        jLabel2Cons.setConstraint("West", Spring.constant(100));
        jLabel2Cons.setConstraint("South", Spring.constant(330));
        jLabel2Cons.setConstraint("North", Spring.constant(300));
        jPanel1.add(jLabel2);
        return jPanel1;
    }
    // </design0>
}

服务器:

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Server extends JFrame
{
   private JTextField enterField;
   private JTextArea displayArea;
   private ObjectOutputStream output;
   private ObjectInputStream input;
   private ServerSocket server;
   private Socket connection;

   String example = "example.txt";
   String myStuff = "MyStuff.txt";

   String command = " ";
    public Server()
   {
       runServer();
   }


   public void runServer()
   {
      try {

         // Step 1: Create a ServerSocket.
         server = new ServerSocket( 5001, 100 );

   waitForConnection();

   getStreams();


   writeData(example, myStuff);
      readData();

   closeConnection();
      }
      catch ( EOFException eofException )
      {
         System.out.println( "Client terminated connection" );
      }
      catch ( IOException ioException )
      {
         ioException.printStackTrace();
      }
   }

   // wait for connection to arrive, then display connection info
   private void waitForConnection() throws IOException
   {
     System.out.println("Waiting for connection\n" );

      connection = server.accept();

      System.out.println( "Connection received from: " + connection.getInetAddress().getHostName() );
   }

   // get streams to send and receive data
   private void getStreams() throws IOException
   {

      output = new ObjectOutputStream( connection.getOutputStream() );

      output.flush();

      input = new ObjectInputStream( connection.getInputStream() );

      System.out.println( "\nGot I/O streams\n" );
   }
   private void readData()
   {
     try
     {
       String com = (String)input.readObject().toString();
       if (com.equals("Load"))
       {
        System.out.println("The server registered your button push");
       }
     }
     catch (IOException classNotFoundException )
  {
       System.out.println( "Unknown object type received" );
  }
  catch (ClassNotFoundException classNotFoundException )
        {
         System.out.println( "Something went wrong on client side 2000" );
     }  
   }
   public void writeData(String s, String e) throws IOException
   {

      try
      {
              output.writeObject(s);
              output.writeObject(e);
              output.flush();

        }
        catch (IOException classNotFoundException )
        {
            System.out.println( "Unknown object type received" );
        }

   }
   // close streams and socket
   private void closeConnection() throws IOException
   {
      System.out.println( "\nUser terminated connection" );
      output.close();
      input.close();
      connection.close();
  }
   public static void main( String args[] )
   {
      Server application = new Server();
   }
}

无论如何,有没有办法执行多种方法,服务器响应每个方法,并且仅在关闭客户端窗口后才关闭连接。

一种方法是传递ArrayList命令。 有关如何执行此操作的详细信息,请参见命令模式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM