简体   繁体   中英

Have Android app send a random number to server

I need to send a random number from Android to a PHP script on my server every 5 seconds. This is for a heart-rhythm simulator for learning purposes. The data from the PHP file is then written to a database. I have spent many hours searching for examples, but they have been hard to understand. I need a simple example of how to do this. Thanks a lot.

Here's an example of how to send a string to a server and read a reply. Just use Math.random() to generate the random number.

String ipAddy = "10.0.2.2 ";

        try {  
            SocketAddress sockaddr = new InetSocketAddress(ipAddy, 1234);
            Socket socket = new Socket();
            socket.connect(sockaddr);

            if (socket.isConnected()) {
                try {
                    Log.d("ClientActivity", "C: Sending command.");
                    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                                .getOutputStream())), true);
                    //Issue some commands here!
                    out.println("Hey Server!");
                    out.flush();


                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    String reversedString = in.readLine();                     
                    System.out.println(reversedString);

                    Log.d("ClientActivity", "C: Sent.");
                } catch (Exception e) {
                    Log.e("ClientActivity", "S: Error", e);
                }finally{
                    socket.close();
                    Log.d("ClientActivity", "C: Closed.");
                }
            }

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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