循环函数和java中的接收字节

时间:2014-11-23 17:39:47

标签: java loops

public class InterfaceGUI implements ActionListener {

private JFrame frame;

private JPanel panelController;
private JPanel panelJack;
private JPanel panelModbus;
private JPanel panelLog;
private JPanel panelStatus;
private JPanel panelToController;
private JPanel panelToJack;

private JLabel lblIpAddController;
private JLabel lblPortController;
private JLabel lblIpAddJack;
private JLabel lblPortJack;
private JLabel lblStatusToController;
private JLabel lblStatusConnToCont;
private JLabel lblIpAddToController;
private JLabel lblIpAddConnToCont;
private JLabel lblPortToController;
private JLabel lblPortConnToCont;
private JLabel lblStatusToJack;
private JLabel lblStatusConnToJack;
private JLabel lblIpAddToJack;
private JLabel lblIpAddConnToJack;
private JLabel lblPortToJack;
private JLabel lblPortConnToJack;
private JLabel lblSlaveId;
private JLabel lblIcon;

private JButton btnConnController;
private JButton btnDiscController;
private JButton btnConnJack;
private JButton btnDiscJack;
private JButton btnConnModbus;

private JTextArea textAreaConnLog;

private JTextField textFieldIpAddController;
private JTextField textFieldPortController;
private JTextField textFieldIpAddJack;
private JTextField textFieldPortJack;
private JTextField textFieldSlaveId;
private Socket myClient;

public byte[] message = new byte[5];
private static final String modbusConn = "modbusconnect";
private static final String modbusDisc = "modbusdisconnect";



/**
 * Launch the application.
 */
public static void main(String[] args){
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                InterfaceGUI window = new InterfaceGUI();
                window.frame.setVisible(true);
                //window.receiveMessage();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public InterfaceGUI() {
    initialize();
}

public void startRunning() throws IOException{
    try {
        while (true){
            System.out.println("receive");
            InputStream inFromServer = myClient.getInputStream();
            DataInputStream in = new DataInputStream(inFromServer);
            in.read(message);
            System.out.println(Arrays.toString(message));
        }
    } catch (EOFException eofexception){
        System.out.println("error");
    }
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 600);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    panelController = new JPanel();
    panelController.setBorder(new TitledBorder(null, "Connection to Controller", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    panelController.setBounds(6, 6, 438, 95);
    frame.getContentPane().add(panelController);
    panelController.setLayout(null);

    lblIpAddController = new JLabel("IP Address :");
    lblIpAddController.setBounds(13, 24, 74, 16);
    panelController.add(lblIpAddController);

    textFieldIpAddController = new JTextField();
    textFieldIpAddController.setBounds(92, 18, 174, 28);
    panelController.add(textFieldIpAddController);
    textFieldIpAddController.setColumns(10);

    btnConnController = new JButton("Connect");
    btnConnController.setBounds(278, 18, 154, 29);
    panelController.add(btnConnController);
    btnConnController.addActionListener(this);

    lblPortController = new JLabel("Port :");
    lblPortController.setBounds(54, 58, 33, 16);
    panelController.add(lblPortController);

    textFieldPortController = new JTextField();
    textFieldPortController.setBounds(92, 52, 174, 28);
    panelController.add(textFieldPortController);
    textFieldPortController.setColumns(10);

    btnDiscController = new JButton("Disconnect");
    btnDiscController.setBounds(278, 52, 154, 29);
    panelController.add(btnDiscController);
    btnDiscController.addActionListener(this);

    panelJack = new JPanel();
    panelJack.setBorder(new TitledBorder(null, "Connection to Jack", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    panelJack.setBounds(6, 113, 289, 95);
    frame.getContentPane().add(panelJack);
    panelJack.setLayout(null);

    lblIpAddJack = new JLabel("IP Address :");
    lblIpAddJack.setBounds(14, 24, 74, 16);
    panelJack.add(lblIpAddJack);

    textFieldIpAddJack = new JTextField();
    textFieldIpAddJack.setBounds(93, 18, 106, 28);
    textFieldIpAddJack.setText("111.111.1.111");
    panelJack.add(textFieldIpAddJack);
    textFieldIpAddJack.setColumns(10);

    btnConnJack = new JButton("Connect");
    btnConnJack.setBounds(200, 20, 86, 29);
    btnConnJack.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
    panelJack.add(btnConnJack);

    lblPortJack = new JLabel("Port :");
    lblPortJack.setBounds(55, 58, 33, 16);
    panelJack.add(lblPortJack);

    textFieldPortJack = new JTextField();
    textFieldPortJack.setBounds(93, 52, 106, 28);
    panelJack.add(textFieldPortJack);
    textFieldPortJack.setColumns(10);

    btnDiscJack = new JButton("Disconnect");
    btnDiscJack.setBounds(200, 52, 86, 29);
    btnDiscJack.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
    panelJack.add(btnDiscJack);

    panelStatus = new JPanel();
    panelStatus.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Connection Status", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    panelStatus.setBounds(6, 220, 438, 126);
    frame.getContentPane().add(panelStatus);
    panelStatus.setLayout(null);

    panelToController = new JPanel();
    panelToController.setBorder(new TitledBorder(null, "Connection to Controller", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    panelToController.setBounds(6, 20, 208, 94);
    panelStatus.add(panelToController);
    panelToController.setLayout(null);

    lblStatusToController = new JLabel("Status");
    lblStatusToController.setBounds(41, 19, 39, 16);
    panelToController.add(lblStatusToController);

    lblStatusConnToCont = new JLabel("DISCONNECTED");
    lblStatusConnToCont.setForeground(Color.RED);
    lblStatusConnToCont.setBounds(85, 19, 117, 16);
    lblStatusConnToCont.setHorizontalAlignment(SwingConstants.CENTER);
    panelToController.add(lblStatusConnToCont);

    lblIpAddToController = new JLabel("IP Address :");
    lblIpAddToController.setBounds(6, 43, 74, 16);
    panelToController.add(lblIpAddToController);

    lblIpAddConnToCont = new JLabel("New label");
    lblIpAddConnToCont.setBounds(113, 43, 61, 16);
    lblIpAddConnToCont.setHorizontalAlignment(SwingConstants.CENTER);
    panelToController.add(lblIpAddConnToCont);

    lblPortToController = new JLabel("Port :");
    lblPortToController.setBounds(47, 66, 33, 16);
    panelToController.add(lblPortToController);

    lblPortConnToCont = new JLabel("New label");
    lblPortConnToCont.setBounds(113, 66, 61, 16);
    lblPortConnToCont.setHorizontalAlignment(SwingConstants.CENTER);
    panelToController.add(lblPortConnToCont);

    panelToJack = new JPanel();
    panelToJack.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Connection to Jack", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    panelToJack.setBounds(218, 20, 214, 94);
    panelStatus.add(panelToJack);
    panelToJack.setLayout(null);

    lblStatusToJack = new JLabel("Status");
    lblStatusToJack.setBounds(41, 19, 39, 16);
    panelToJack.add(lblStatusToJack);

    lblStatusConnToJack = new JLabel("DISCONNECTED");
    lblStatusConnToJack.setForeground(Color.RED);
    lblStatusConnToJack.setBounds(85, 19, 123, 16);
    lblStatusConnToJack.setHorizontalAlignment(SwingConstants.CENTER);
    panelToJack.add(lblStatusConnToJack);

    lblIpAddToJack = new JLabel("IP Address :");
    lblIpAddToJack.setBounds(6, 43, 74, 16);
    panelToJack.add(lblIpAddToJack);

    lblIpAddConnToJack = new JLabel("New label");
    lblIpAddConnToJack.setBounds(116, 43, 61, 16);
    lblIpAddConnToJack.setHorizontalAlignment(SwingConstants.CENTER);
    panelToJack.add(lblIpAddConnToJack);

    lblPortToJack = new JLabel("Port :");
    lblPortToJack.setBounds(47, 66, 33, 16);
    panelToJack.add(lblPortToJack);

    lblPortConnToJack = new JLabel("New label");
    lblPortConnToJack.setBounds(116, 66, 61, 16);
    lblPortConnToJack.setHorizontalAlignment(SwingConstants.CENTER);
    panelToJack.add(lblPortConnToJack);

    panelModbus = new JPanel();
    panelModbus.setBorder(new TitledBorder(null, "Modbus", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    panelModbus.setBounds(296, 113, 148, 95);
    frame.getContentPane().add(panelModbus);
    panelModbus.setLayout(null);

    lblSlaveId = new JLabel("ID :");
    lblSlaveId.setBounds(33, 24, 22, 16);
    panelModbus.add(lblSlaveId);

    textFieldSlaveId = new JTextField();
    textFieldSlaveId.setBounds(60, 18, 82, 28);
    panelModbus.add(textFieldSlaveId);
    textFieldSlaveId.setColumns(10);

    lblIcon = new JLabel("icon");
    lblIcon.setBounds(17, 52, 32, 35);
    panelModbus.add(lblIcon);
    Image imgDisconnect = new ImageIcon(this.getClass().getResource("red-unlock-icon.png")).getImage();
    lblIcon.setIcon(new ImageIcon(imgDisconnect));

    btnConnModbus = new JButton("Connect");
    btnConnModbus.setBounds(60, 51, 82, 29);
    panelModbus.add(btnConnModbus);

    panelLog = new JPanel();
    panelLog.setBorder(new TitledBorder(null, "Connection Log", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    panelLog.setBounds(6, 358, 438, 214);
    frame.getContentPane().add(panelLog);
    panelLog.setLayout(null);

    textAreaConnLog = new JTextArea();
    textAreaConnLog.setBounds(6, 19, 426, 189);
    panelLog.add(textAreaConnLog);
}

@Override
public void actionPerformed(ActionEvent ae) {
    // TODO Auto-generated method stub
    if(ae.getSource() instanceof JButton){
        if(ae.getSource() == btnConnController){
            //check validity ip dan port number later on
            try {
                myClient = new Socket("192.168.1.104", 1234);
                if(myClient.isConnected() == true){
                    textAreaConnLog.setText("connected to 192.168.1.104 at port 1234");
                    lblStatusConnToJack.setText("CONNECTED");
                    lblStatusConnToJack.setForeground(Color.GREEN);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
         }
    }
}

}

我目前正在构建一个客户端程序,以便服务器接收广播的消息。只是想让事情变得清楚,方法startRunning()是否会在没有人调用的情况下继续循环,这是正确的吗?此外,传入的数据是字节的形式,我可以使用方法.read(消息)读取数据并将其存储到消息[]?

1 个答案:

答案 0 :(得分:0)

方法startRunning()在没有人调用的情况下会继续自行循环是否正确?

你必须至少调用一次startRunning()方法,以便它开始执行它的代码;之后,while块将继续无限循环,除非发生异常。

此外,传入的数据是以字节的形式,我可以使用.read(message)方法读取数据并将其存储到消息[]中吗?

是的,你可以。有关规范,请参阅此link

如果我可以添加提示:

private boolean Continue = true;

public void setContinue(boolean b)
{
     Continue = b;
} 


public void startRunning() throws IOException
{
    DataInputStream in;
    try
     {
        while (Continue)
        {
            System.out.println("receive");
            InputStream inFromServer = myClient.getInputStream();
            in = new DataInputStream(inFromServer);
            in.read(message);
            System.out.println(Arrays.toString(message));
        }
    } 
    catch (EOFException eofexception)
    {
        System.out.println("error");
    }
    catch(Exception ex)
    {
        in.close();
        throw ex;
    }
}

注意while循环的条件。如果您需要,这将使您的代码对中断更敏感;溪流不应无限开放。

此外,您应该在发生异常时关闭流。