没有收到服务器的响应:Java.net.SocketException:recvfrom failed:ECONNRESET

时间:2015-06-02 08:55:51

标签: java android mysql web-services server

我正在尝试根据用户提供的输入从服务器读取数据。我在尝试从服务器读取时收到套接字异常。请任何让我知道我在做什么错误。我试图从我的移动设备执行应用程序,服务器是本地主机。

我在asyncTask方法的以下行中遇到异常:

// Get the server response
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

以下是我的代码:

import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;


public class MainActivity extends AppCompatActivity {

    private static Toolbar toolbar;
    private static EditText userName, password;
    private int result, count;
    TextView content;
    private String enteredUserName, enteredPassword, value, text = "";
    private ImageButton signUp, signIn;


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

        // Initializing and setting ToolBar and Hiding ActionBar
//        ActionBar actionBar = getActionBar();
//        actionBar.hide();

        toolbar = (Toolbar) findViewById(R.id.appBar);
        setSupportActionBar(toolbar);
        toolbar.setTitleTextColor(Color.WHITE);

        userName = (EditText) findViewById(R.id.editTextUserName);
        password = (EditText) findViewById(R.id.editTextPassword);
        signUp = (ImageButton) findViewById(R.id.buttonSignUp);
        signIn = (ImageButton) findViewById(R.id.imageButtonLogin);
        content = (TextView) findViewById(R.id.textViewContent);

        //Getting the value of UserName and Password fields to check whether account has already been created
        SQLiteDataBaseAdapter db = new SQLiteDataBaseAdapter(this);
        db.getUserNamePassword();

        count = db.getStatusRowCount();

        if(count != 0) {

            value = db.getStatusValue();

            Log.d("iFocus", "The value of Value is " + value);

        }


    }

    public void onClickLogin(View view) {

  // get The User name and Password
        enteredUserName = userName.getText().toString();
         enteredPassword = password.getText().toString();



        //check if user is admin

        if(enteredUserName.contains("admin") && enteredPassword.contains("admin")){

            Intent intent = new Intent(this, AdminActivity.class);
            startActivity(intent);
            finish();
            return;
        }


        new StatusCheck().execute();

        if (text.equals("1")){
            return;
        }







        //Check if userName or Password is blank
        if (enteredUserName.isEmpty() || enteredPassword.isEmpty()) {
            Toast.makeText(this, " User Name or Password cannot be blank. Enter Valid User Name and Password \n \n If user does not exist, sign up and create an account", Toast.LENGTH_LONG).show();
            return;
        }

        new PasswordCheck().execute();


    }

    public void onClickSignUp(View view){

        if(count == 0) {

            Intent intent = new Intent(this, SignUpActivity.class);
            startActivity(intent);
            return;
        }

        else {

            Toast.makeText(this, "Account already exists, Please try logging in with the existing account credentials.", Toast.LENGTH_LONG).show();
            return;
        }


        }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

我在以下异步任务方法中收到错误。在阅读服务器的响应时。

private class StatusCheck extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... params) {


          // Create data variable for sent values to server
            String data = null;
            try {
                data = URLEncoder.encode("enteredusername", "UTF-8")
                        + "=" + URLEncoder.encode(enteredUserName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            BufferedReader reader=null;
            System.setProperty("http.keepAlive", "false");

            // Send data
            try
            {

                // Defined URL  where to send data
                URL url = new URL("http://10.0.2.2/loginstatuscheck.php");

                // Send POST data request
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write( data );
                wr.flush();

                // Get the server response
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null;

                // Read Server Response
                while((line = reader.readLine()) != null)
                {
                    // Append server response in string
                    sb.append(line);
                }


                text = sb.toString();
            }
            catch(Exception ex) {
                Log.e("iFocus", ""+ex);
            }
            try
            {

            }
            finally
            {
                try
                {

                    reader.close();
                }

                catch(Exception ex) {}
            }

            // Show response on activity
//            content.setText( text  );
            Log.d("iFocus", "The value of the response is " + text);



            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(getApplicationContext(), ""+text, Toast.LENGTH_LONG).show();

            if (text.equals("1")){
                Toast.makeText(getApplicationContext(), "The Account is still under Moderation. Account is not yet Active. Please try after some time", Toast.LENGTH_LONG).show();
            signUp.setClickable(false);
            signUp.setEnabled(false);
            signIn.setEnabled(false);
            signIn.setClickable(false);
            return;
            }
            else {
                Toast.makeText(getApplicationContext(), "The Account has been Activated Successfully", Toast.LENGTH_LONG).show();
            signUp.setClickable(false);
            signUp.setEnabled(false);
            signIn.setEnabled(true);
            signIn.setClickable(true);
            }


            }
        }


    private class PasswordCheck extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... params) {


            // get The User name and Password
            enteredUserName = userName.getText().toString();
            enteredPassword = password.getText().toString();

            // Create data variable for sent values to server
            String data = null;
            try {
                data = URLEncoder.encode("enteredusername", "UTF-8")
                        + "=" + URLEncoder.encode(enteredUserName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            BufferedReader reader=null;
            System.setProperty("http.keepAlive", "false");

            // Send data
            try
            {

                // Defined URL  where to send data
                URL url = new URL("http://10.0.2.2/passwordretreive.php");

                // Send POST data request
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write( data );
                wr.flush();

                // Get the server response
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null;

                // Read Server Response
                while((line = reader.readLine()) != null)
                {
                    // Append server response in string
                    sb.append(line);
                }


                text = sb.toString();
            }
            catch(Exception ex) {
                Log.e("iFocus", ""+ex);
            }
            try
            {

            }
            finally
            {
                try
                {

                    reader.close();
                }

                catch(Exception ex) {}
            }

            // Show response on activity
//            content.setText( text  );
            Log.d("iFocus", "The value of the response is " + text);



            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if (text.equals(enteredPassword)){

                Toast.makeText(getApplicationContext(), "Congrats: Login Successful", Toast.LENGTH_SHORT).show();

                //Calling the next screen after successful Login
                Intent intent = new Intent(getApplicationContext(), MainScreen.class);
                intent.putExtra("UserName", enteredUserName);
                startActivity(intent);
                finish();

            } else {
                //Displaying message for unsuccessful login attempt
                Toast.makeText(getApplicationContext(), "User Name or Password does not match", Toast.LENGTH_LONG).show();
            }



        }
    }

    }

欢迎所有建议。提前致谢。请帮我解决这个问题。我很久很难挣扎。

1 个答案:

答案 0 :(得分:1)

错误已解决。我曾说我试图从我的移动设备上测试它,所以我需要给我的电脑的网址,因为它不是模拟器,我不应该给10.0.2.2。更改URL并提供我的系统URL就可以了。希望它有所帮助。