使用employee类在客户端和服务器之间传递的对象

时间:2015-10-07 07:33:05

标签: java sockets server

我需要修改代码,以便在客户端和服务器之间传递对象而不是单个数据。这需要我定义自己的类Employee并创建Employee类的对象以在客户端和服务器之间传递

客户端类

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class MultiClient extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    private JTextField textField_1;
    private JTextField textField_2;
    private JTextField textField_3;


    /**
     * Launch the application.
     */

    // IO streams
    private DataOutputStream toServer;
    private DataInputStream fromServer;

    public static void main(String[] args) {
        Employee no1 = new Employee();
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MultiClient frame = new MultiClient();
                    frame.setVisible(true);
                    frame.setTitle("Work Hard Client");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * Create the frame.
     */
    public MultiClient() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 650);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JTextArea jta = new JTextArea();
        jta.setBounds(12, 391, 408, 199);
        contentPane.add(jta);

        try {
            // Create a socket to connect to the server
            Socket socket = new Socket("localhost", 8000);

            // Create an input stream to receive data from the server
            fromServer = new DataInputStream(
                    socket.getInputStream());

            // Create an output stream to send data to the server
            toServer =
                    new DataOutputStream(socket.getOutputStream());
        }
        catch (IOException ex) {
            jta.append(ex.toString() + '\n');
        }

        JLabel lblEnterMonths = new JLabel("Enter months:");
        lblEnterMonths.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblEnterMonths.setBounds(12, 36, 119, 29);
        contentPane.add(lblEnterMonths);

        JLabel lblEnterDays = new JLabel("Enter days:");
        lblEnterDays.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblEnterDays.setBounds(12, 100, 119, 29);
        contentPane.add(lblEnterDays);

        JLabel lblEnterPayrate = new JLabel("Enter payrate:");
        lblEnterPayrate.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblEnterPayrate.setBounds(12, 154, 119, 29);
        contentPane.add(lblEnterPayrate);

        JLabel lblEnterHours = new JLabel("Enter hours:");
        lblEnterHours.setFont(new Font("Tahoma", Font.PLAIN, 16));
        lblEnterHours.setBounds(12, 208, 119, 29);
        contentPane.add(lblEnterHours);

        textField = new JTextField();
        textField.setFont(new Font("Tahoma", Font.PLAIN, 15));
        textField.setBounds(233, 28, 187, 46);
        contentPane.add(textField);
        textField.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setFont(new Font("Tahoma", Font.PLAIN, 15));
        textField_1.setColumns(10);
        textField_1.setBounds(233, 92, 187, 46);
        contentPane.add(textField_1);

        textField_2 = new JTextField();
        textField_2.setFont(new Font("Tahoma", Font.PLAIN, 15));
        textField_2.setColumns(10);
        textField_2.setBounds(233, 146, 187, 46);
        contentPane.add(textField_2);

        textField_3 = new JTextField();
        textField_3.setFont(new Font("Tahoma", Font.PLAIN, 15));
        textField_3.setColumns(10);
        textField_3.setBounds(233, 200, 187, 46);
        contentPane.add(textField_3);

        JButton btnCalulatePay = new JButton("Calulate Pay");

        btnCalulatePay.addActionListener(new ActionListener() {


            public void actionPerformed(ActionEvent e) {
                try {
                    int noMonths = (int)
                            ((Double.parseDouble(textField.getText()))
                                    );
                    toServer.writeInt(noMonths);

                    int noDays = (int)
                            ((Double.parseDouble(textField_1.getText()))
                                    );
                    toServer.writeInt(noDays);

                    double payRate = (double)
                            ((Double.parseDouble(textField_2.getText()))
                                    );      
                    toServer.writeDouble(payRate);

                    double  hours = (double)
                            ((Double.parseDouble(textField_3.getText()))
                                    );
                    toServer.writeDouble(hours);

                    double sum = (noMonths*noDays)*(payRate*hours);
                    // Send the pay to the server
                    toServer.flush();
                    // Get area pay the server
                    double Pay = fromServer.readDouble();

                    jta.append("Pay is " + sum+ "\n");
                    jta.append("Pay received from the server is "
                            + sum + '\n');
                }
                catch (IOException ex) {
                    System.err.println(ex);
                }
            }
        });
        btnCalulatePay.setFont(new Font("Tahoma", Font.PLAIN, 14));
        btnCalulatePay.setBounds(12, 305, 119, 25);
        contentPane.add(btnCalulatePay);

        JButton btnClear = new JButton("Clear");
        btnClear.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                textField.setText(null);
                textField_1.setText(null);
                textField_2.setText(null);
                textField_3.setText(null);
            }
        });
        btnClear.setFont(new Font("Tahoma", Font.PLAIN, 14));
        btnClear.setBounds(143, 305, 75, 25);
        contentPane.add(btnClear);

        JButton btnHelp = new JButton("Help");
        btnHelp.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                JOptionPane.showMessageDialog (null, "Message", "Title", JOptionPane.INFORMATION_MESSAGE);  

            }
        });
        btnHelp.setFont(new Font("Tahoma", Font.PLAIN, 14));
        btnHelp.setBounds(233, 305, 75, 25);
        contentPane.add(btnHelp);

        JButton btnExit = new JButton("Exit");
        btnExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        btnExit.setFont(new Font("Tahoma", Font.PLAIN, 14));
        btnExit.setBounds(332, 306, 75, 25);
        contentPane.add(btnExit);

    }
}

服务器类

import java.awt.BorderLayout;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class MultiClientServer extends JFrame {
  private JTextArea jta = new JTextArea();

  public static void main(String[] args) {
      Employee employee = null;
    new MultiClientServer();

  }

  public MultiClientServer() {
    setLayout(new BorderLayout());
    add(new JScrollPane(jta), BorderLayout.CENTER);

    setTitle("Work Hard Server");
    setSize(500, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true); // It is necessary to show the frame here!

    try {
      ServerSocket serverSocket = new ServerSocket(8000);
      jta.append("MultiThreadServer started at " + new Date() + '\n');

      int clientNo = 1;

      while (true) {
        Socket socket = serverSocket.accept();

        HandleAClient task = new HandleAClient(socket);


        new Thread(task).start();

        clientNo++;
      }
    }
    catch(IOException ex) {
      System.err.println(ex);
    }
  }


  class HandleAClient implements Runnable {
    private Socket socket; 

    /** Construct a thread */
    public HandleAClient(Socket socket) {
      this.socket = socket;
    }

    /** Run a thread */
    public void run() {
      try {

        DataInputStream inputFromClient = new DataInputStream(
          socket.getInputStream());
        DataOutputStream outputToClient = new DataOutputStream(
          socket.getOutputStream());


        while (true) {

          int noMonths = inputFromClient.readInt();
          int noDays = inputFromClient.readInt();
          double payRate = inputFromClient.readDouble();
          double hours = inputFromClient.readDouble();


        double sum = (noMonths*noDays)*(payRate*hours);

          outputToClient.writeDouble(sum);
          jta.append("Months received from client: " +
                  noMonths + '\n');
          jta.append("Days received from client: " +
                  noDays + '\n');
          jta.append("Rate received from client: " +
                  payRate + '\n');
          jta.append("Hours received from client: " +
                  hours + '\n');

          jta.append("pay calculated and sent is: " +
                  sum + '\n');
        }
      }
      catch(IOException e) {
        System.err.println(e);
      }
    }
  }
}

员工类

public class Employee implements Serializable {

    private int noMonths;
    private int noDays;
    private double payRate;
    private double hours;

    Employee( int mon, int days, double pay, double hour ) 
    {
        noMonths = mon;
        noDays = days;
        payRate = pay;
        hours = hour;
    }

    public Employee() {
        // TODO Auto-generated constructor stub
    }

    public int getNoMonths() {
        return noMonths;
    }

    public void setNoMonths(int noMonths) {
        this.noMonths = noMonths;
    }

    public int getNoDays() {
        return noDays;
    }

    public void setNoDays(int noDays) {
        this.noDays = noDays;
    }

    public double getPayRate() {
        return payRate;
    }

    public void setPayRate(double payRate) {
        this.payRate = payRate;
    }

    public double getHours() {
        return hours;
    }

    public void setHours(double hours) {
        this.hours = hours;
    }
}

1 个答案:

答案 0 :(得分:1)

我认为最简单的方法是使用诸如XStream之类的内容,它会将您的对象更改为XML格式。

然后,您将使用writeUTF(String s)Employee对象编写为XML字符串,然后使用readUTF()来恢复XML字符串。

然后,您可以再次使用XStream将其更改回您的对象。

编辑:

根据您的评论,我的理解是您需要更改代码,以便您不发送对象的属性值,而是编写对象本身。

我建议的方法将Employee对象更改为XML字符串。然后,您可以将XML字符串写入流并将其读回,从而最终在服务器端使用XML字符串。

然后,您将再次使用XStream将XML字符串更改为其对应的对象。

您可以使用其他方法将Employee类序列化为字节数组并传输它。在我看来,这种方法的问题在于,如果您希望通过其他语言连接到系统,它可能会导致问题,因为序列化可能已关闭。

XML序列化至少允许您手动解析对象,从而为您提供后备计划。