由于没有收到服务器的响应:java.net.SocketException异常:recvfrom的失败:ECONNRESET [英] Not receiving response from server: Java.net.SocketException: recvfrom failed: ECONNRESET

查看:2226
本文介绍了由于没有收到服务器的响应:java.net.SocketException异常:recvfrom的失败:ECONNRESET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从基于由用户给出的输入的服务器读取数据。我试图从服务器读取时收到套接字异常。请任何关于让我知道我在做什么错误。我想从我的移动设备执行应用程序和服务器是本地主机。

I am trying to read data from the server based on the input given by the user. I am receiving the socket exception when trying to read from the server. Please any on let me know what mistake am I doing. I am trying to execute the application from my mobile device and server is local host.

我在下面一行的AsyncTask方法越来越例外

I am getting exception in the following line of asyncTask method:

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

以下是我的code:

Following is my code:

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;
    }

我收到了以下任务异步方法的错误。而从服务器读取响应。

I am getting the error in the following async task method. While reading the response from the server.

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



        }
    }

    }

所有建议都欢迎。提前致谢。请帮我走出这个问题。我从很长一段时间苦苦挣扎。

All suggestions are welcome. Thanks in advance. Please help me come out of this issue. I am struggling hard from long time.

推荐答案

错误解决。我说我想从我的移动设备进行测试,所以我需要给我的电脑的网址,因为它不是一个模拟器我不应该给10.0.2.2。更改URL,并给予我的系统网址的伎俩。希望它可以帮助其他人。

Error solved. I had said I am trying to test it from my mobile device, so I need to give the url of my computer since its not an emulator I am not supposed to give 10.0.2.2. Changing the URL and giving my system URL did the trick. Hope it helps some one.

这篇关于由于没有收到服务器的响应:java.net.SocketException异常:recvfrom的失败:ECONNRESET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆