Data from Android Mobile to Java Application through Socket

南笙酒味 提交于 2019-12-25 02:06:29

问题


I want to transfer data from Android device to the java desktop server. I have a text and button. As I press the button on the device, the text should be displayed on the java desktop server. I also have added AsyncTask in the client. The error code has also been added. The port i have used is 4444 and the ip address I used is of my local host address.

I am doing a very silly mistake. Can you please guide me.

I run the server code, it first gives me : Server started. Listening to the port 4444.

Now, I run the client code and write something on my mobile. As I press my button, it gives me error. And the app crashes and closes. I am a new one. Thanks in advance.

Client Code :

        public class MainActivity extends Activity {

            @Override
            public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            textField = (EditText) findViewById(R.id.editText1); //reference to the text field
            button = (Button) findViewById(R.id.button1);   //reference to the send button

            //Button press event listener
            button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

            messsage = textField.getText().toString(); //get the text message on the text field
            textField.setText("");      //Reset the text field to blank

            try {

             client = new Socket("134.190.162.165", 4444);  //connect to server
             printwriter = new PrintWriter(client.getOutputStream(),true);
             printwriter.write(messsage);  //write the message to output stream

             printwriter.flush();
             printwriter.close();
             client.close();   //closing the connection

            } catch (UnknownHostException e) {
             e.printStackTrace();
            } catch (IOException e) {
             e.printStackTrace();
            }
            }
            });

            }


            public class Asynctask extends AsyncTask<View, Integer, Socket>
            {
                private static final String IP_ADDRESS = "134.190.162.165";  // Toshiba laptop
            //  private static final String IP_ADDRESS = "10.0.0.2";  // Toshiba laptop
                private static final int DEST_PORT = 4444;

                private EditText mTextField;

                /**
                 * Store provided views (used later in onPostExecute(...)).
                 * 
                 * Create socket to communicate with server (blocking call).
                 */
                protected Socket doInBackground(View... params)
                {
                    // Store provided views.
                    if (params.length != 1)
                        throw new IllegalArgumentException();

                    mTextField = (EditText) params[0];


                    // Create socket.
                    Socket client = null;

                    try
                    {
                        client = new Socket(IP_ADDRESS, DEST_PORT); // connect to server
                    } catch (UnknownHostException e)
                    {
                        e.printStackTrace();
                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }

                    return client;
                }

                /**
                 * Write to server.
                 */
                protected void onPostExecute(Socket client)
                {
                    try
                    {
                        PrintWriter printwriter;
                        String messsage;

                        messsage = mTextField.getText().toString(); // get the text message on the text field
                        mTextField.setText(""); // Reset the text field to blank

                        printwriter = new PrintWriter(client.getOutputStream(), true);
                        printwriter.write(messsage); // write the message to output stream

                        printwriter.flush();
                        printwriter.close();

                        client.close();
                    } 
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            }


         }

Server Code:

        public class server {

            private static ServerSocket serverSocket;
            private static Socket clientSocket;
            private static InputStreamReader inputStreamReader;
            private static BufferedReader bufferedReader;
            private static String message;

            public static void main(String[] args) {

                try {
                    serverSocket = new ServerSocket(4444);  //Server socket

                } catch (IOException e) {
                    System.out.println("Could not listen on port: 4444");
                }

                System.out.println("Server started. Listening to the port 4444");

                while (true) {
                    try {

                        clientSocket = serverSocket.accept();   //accept the client connection
                        inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
                        bufferedReader = new BufferedReader(inputStreamReader); //get the client message
                        message = bufferedReader.readLine();

                        System.out.println(message);
                        inputStreamReader.close();
                        clientSocket.close();

                    } catch (IOException ex) {
                        System.out.println("Problem in message reading");
                    }
                }

            }
        }

The error which I get is:

    FATAL EXCEPTION: main
     android.os.NetworkOnMainThreadException
     android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
    libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
    libcore.io.IoBridge.connectErrno(IoBridge.java:127)
    libcore.io.IoBridge.connect(IoBridge.java:112)
    java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
    java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    java.net.Socket.startupSocket(Socket.java:572)
    java.net.Socket.tryAllAddresses(Socket.java:127)
     java.net.Socket.<init>(Socket.java:177)
     java.net.Socket.<init>(Socket.java:149)
    com.example.client.MainActivity$1.onClick(MainActivity.java:42)
    android.view.View.performClick(View.java:3567)

In the manifest file, I have added all the requirements. It does not give any compile time error.

I checked from many websites but the code which is working is this only. But I dont know where I am making mistake in running it or somewhere else. 

If any other option is there, please suggest me, i am scratching my head since long

Thanks

回答1:


Your code seems very confusing. The client seems to have code for doing the network connection and I/O both on the main thread (in the OnClickListener attached to button) and in the AsyncTask (which is never created). Try this for an OnClickListener:

button.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        message = textField.getText().toString(); //get the text message on the text field
        textField.setText("");      //Reset the text field to blank
        new Asynctask().execute(message);
    }
});

But you have another problem: while your AsyncTask is (correctly) making the socket connection in doInBackground, it is incorrectly doing the network I/O in onPostExecute. The network I/O also needs to be done in the background. Try this for an AsyncTask:

public class Asynctask extends AsyncTask<String, Void, Void> {
    private static final String IP_ADDRESS = "134.190.162.165";  // Toshiba laptop
    //  private static final String IP_ADDRESS = "10.0.0.2";  // Toshiba laptop
    private static final int DEST_PORT = 4444;

    private EditText mTextField;

    /**
     * Store provided views (used later in onPostExecute(...)).
     * 
     * Create socket to communicate with server (blocking call).
     */
    protected Void doInBackground(String... messages) {
        if (messages.length != 1) { return null; }
        String message = messages[0];

        // Create socket.
        Socket client = null;

        try {
            client = new Socket(IP_ADDRESS, DEST_PORT); // connect to server
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Write to server.
        try {
            printwriter = new PrintWriter(client.getOutputStream(), true);
            printwriter.write(messsage); // write the message to output stream

            printwriter.flush();
            printwriter.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

The above is entirely untested, so it may not be exactly right. I also didn't look at your server code; this answer just addresses the NetworkOnMainThreadException problem.



来源:https://stackoverflow.com/questions/21818076/data-from-android-mobile-to-java-application-through-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!