java - 未收到来自服务器 : Java.net.SocketException 的响应:recvfrom 失败:ECONNRESET

标签 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();
            }



        }
    }

    }

欢迎所有建议。提前致谢。请帮我解决这个问题。长期以来,我一直在努力奋斗。

最佳答案

错误已解决。我说过我正在尝试通过我的移动设备对其进行测试,所以我需要提供我的计算机的 url,因为它不是我不应该提供的模拟器 10.0.2.2。更改 URL 并提供我的系统 URL 就可以了。希望对某些人有所帮助。

关于java - 未收到来自服务器 : Java.net.SocketException 的响应:recvfrom 失败:ECONNRESET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30591544/

相关文章:

java - PHP 中的只读 for 循环

java - 如何提高递归方法的性能?

android - 如何在我的 OSM 应用程序上显示路线

Android Studio 4.1 模拟器崩溃

php - 键 'bla bla bla bla ' 上的重复条目 'username'?

java - 批量更新从更新 [0] 返回了意外的行数;

java - 动态地将textview放在relativelayout android中的另一个 View 之上

android - Android 中的 HTML 选择多个呈现奇怪?

Mysql查询支付

MySQL:当每个订单有多个账单表(以及多次付款)时,仅显示有余额的订单