简体   繁体   English

如何使用来自服务器的随机数在客户端 JAVA SOCKET PROGRAMMING 上随机显示图像数组中的图像

[英]How to use random number from server to randomly display image from an array of images on client JAVA SOCKET PROGRAMMING

I have this project where I have to take random number from server and use it to randomly display a picture from an array on client side a button click.我有这个项目,我必须从服务器获取随机数并使用它从客户端的数组中随机显示图片,单击按钮。 So basically this random number from server should be the index of some image from array of images.所以基本上这个来自服务器的随机数应该是图像数组中某些图像的索引。

Here is the server:这是服务器:


    public class MemoryGameServer {
    public int[] array; 


    //Method to generate random number 

    public int getRandom(){
        this.array = new int[4];
       Random random = new Random();
        int randomNumber = random.nextInt(array.length);
        return randomNumber;
    } 






    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        ServerSocket listener = new ServerSocket(1243);
        System.out.println("Server is connected..");
        try {
            while (true) {
                Socket socket = listener.accept();
                System.out.println("Client is connected..");
                MemoryGameServer server = new MemoryGameServer();

                DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                dos.writeInt(server.getRandom()); // Sending random number as integer
                dos.flush();


            }
        } catch (IOException ex) {
            System.out.println(ex);
        }
    }
} 

Here is the client:这是客户端:

public class MemoryGameClient extends javax.swing.JFrame {

  public String[] images = {"0.jpg", "1.jpg", "2.jpg", "3.jpg"};
  public int n;
  Socket socket;



    public int randomPicture () throws IOException{

        try{

        DataInputStream dis = new DataInputStream(socket.getInputStream());

        this.n = dis.readInt();
        System.out.println("Random number form server: " +n);





        } catch (Exception ex){

        }
        return n;
    }



    /**
     * Creates new form MemoryGameClient
     */
    public MemoryGameClient() {
        initComponents();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("2x2");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("2x4");

        jLabel1.setName("lblImage"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(54, 54, 54)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 89, Short.MAX_VALUE)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(64, 64, 64))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(20, 20, 20))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 210, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         


          //String image1 = images[randomImage1];
          jLabel1.setIcon(new ImageIcon("src\\Images\\" ));
          //jLabel2.setIcon(new ImageIcon("src\\Images\\" +image));
          //jLabel3.setIcon(new ImageIcon("src\\Images\\" +image1));
          //jLabel4.setIcon(new ImageIcon("src\\Images\\" +image1));





    }                                        

    /**
     * @param args the command line arguments
     */

    public void connectToServer() throws IOException {

        // Get the server address from a dialog
// box.
        String serverAddress = "localhost";

        // Make connection and initialize streams
        try{
        socket = new Socket("localhost", 1243);

                /* InputStream is = socket.getInputStream();

                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                this.str = br.readLine();
                System.out.println("Random number form server: " +str);

                */

        } catch(Exception ex)
        { 
            JOptionPane.showMessageDialog(this, "Nema servera");
        }
    }
    public static void main(String args[]) throws IOException {

        MemoryGameClient client = new MemoryGameClient();
        client.setVisible(true);
        client.connectToServer();
        client.randomPicture();


        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MemoryGameClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MemoryGameClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MemoryGameClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MemoryGameClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    // End of variables declaration                   
}

It is sending random number to the client, i just don't know how to use that number to take a random image from this String [] images array.它正在向客户端发送随机数,我只是不知道如何使用该数字从这个 String [] 图像数组中获取随机图像。 It should work on the click of the button 2x2 or 2x4 (i have later to make it display 2x2 or 2x4 pictures, but i can do it on my own).它应该在单击 2x2 或 2x4 按钮时起作用(我稍后要让它显示 2x2 或 2x4 图片,但我可以自己做)。

Thanks for helping.感谢您的帮助。

 int num = new Random().nextInt(4) + 1;// would represent a random number between 1-4.

switch (num) {
            case 0:
                jLabel1.setIcon(new ImageIcon("src\\Images\\"+images[num]));
                break;
            case 1:
                jLabel2.setIcon(new ImageIcon("src\\Images\\"+images[num]));
                break;
            case 2:
                jLabel3.setIcon(new ImageIcon("src\\Images\\"+images[num]));
                break;
            case 3:
                jLabel4.setIcon(new ImageIcon("src\\Images\\"+images[num]));
                break;
            default:
                //error
        }

Hope this helps.希望这可以帮助。

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

相关问题 如何在套接字编程中从Server(server.java)socket连续侦听PHP(client.php)套接字 - how to continuously listen PHP(client.php) socket from Server(server.java)socket in socket programming 服务器如何知道客户端的端口号,它将使用它使用 Java 编程套接字将响应发送到客户端? - How the server knows the port number of the client in which it will use it to send the responses to the client using java programming socket? 客户端无法从服务器套接字编程Java接收消息 - Client not able to receive messages from Server Socket programming Java Java套接字编程阻止对服务器和客户端的读写 - java socket programming blocking on read and write to and from server&client Java套接字编程中将文件从多个客户端发送到单个服务器 - File sending from multiple client to Single server in Java Socket Programming 通过套接字从服务器到客户端的图像 - Images from server to client by socket 将图像从套接字服务器(java)发送到套接字客户端(python) - sending Image from Socket server (java) to socket client (python) Java中的客户端套接字编程-从服务器端写入客户端套接字的麻烦 - Client-socket programming in Java - trouble with writing to the client socket from server side 套接字编程客户端服务器Java - socket programming client server java Java Socket编程服务器客户端 - java Socket programming Server Client
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM