简体   繁体   中英

java.net.socket ConnectException ETIMEEDOUT

I'm trying to connect server socket using android. Please check the code below. I'm trying to send data from android to server as well as send data back to android from server but it is causing timeout exception at android side.

package com.example.orderdish;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MenuActivity extends Activity {

    Button vegButton, nonVegButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

        vegButton = (Button) findViewById(R.id.btn_veg);
        nonVegButton = (Button) findViewById(R.id.btn_non_veg);
    }

    public void openCategory(View view) {
        Button button = (Button)view;
        Toast.makeText(getApplicationContext(), button.getText().toString() + " selected", Toast.LENGTH_LONG).show();
        //Intent intent = new Intent(getApplicationContext(), ListCategoryActivity.class);
        //startActivity(intent);
         MyClientTask myClientTask = new MyClientTask(
                   "my ip",
                   1234);
                 myClientTask.execute();
    }

     public class MyClientTask extends AsyncTask<Void, Void, String> {

          String dstAddress;
          int dstPort;
          String response = "";
          DataOutputStream dataOutputStream = null;
          DataInputStream dataInputStream = null;
          MyClientTask(String addr, int port){
           dstAddress = addr;
           dstPort = port;
          }

          @Override
          protected String doInBackground(Void... arg0) {

           Socket socket = null;

           try {
               Timer timer = new Timer(3000);
               timer.start();
               //Connect to remote host
               socket = new Socket(dstAddress, dstPort);
               Log.v("MenuActivity: ", "Connected to 1234 port");

               //Reset timer - timeout can occur on connect
           // InputStream inputStream = socket.getInputStream();
               //create data output stream for writing
               PrintStream pout = new PrintStream(socket.getOutputStream());
              //dataOutputStream = new DataOutputStream(socket.getOutputStream());


           // dataOutputStream.writeUTF("v");

               //create data input stream for reading
               DataInputStream din = new DataInputStream(socket.getInputStream());

               //Print hello message
               pout.println("Hello world");

               //Reset timer - timeout is likely to occur during the read
               timer.reset();

               //print message from server

          //  dataInputStream = new DataInputStream(socket.getInputStream());
         //   response = dataInputStream.readUTF();
         //   Log.v("MenuActivity", "hi.." + dataInputStream.readUTF());
            ByteArrayOutputStream byteArrayOutputStream = 
                          new ByteArrayOutputStream(1024);
            byte[] buffer = new byte[1024];

            int bytesRead;


            /*
             * notice:
             * inputStream.read() will block if no data return
             */
                     while ((bytesRead = din.read(buffer)) != -1){
                         byteArrayOutputStream.write(buffer, 0, bytesRead);
                         response += byteArrayOutputStream.toString("UTF-8");
                     }
                     Log.v("MenuActivity ", response);

                     timer.stop();
           } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "UnknownHostException: " + e.toString();
           } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "IOException: " + e.toString();
           }finally{
            if(socket != null){
             try {
              socket.close();
             } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
             }
            }
           }
           return response;
          }

          @Override
          protected void onPostExecute(String result) {
         //  textResponse.setText(response);
            Log.v("MenuActivity", result);
           super.onPostExecute(result);
          }

         }

}



package com.orderdish.main;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

import com.google.gson.Gson;



public class Test {
//  List<Menu> menuList;
    public static void main(String args[])  {

            ServerSocket serverSocket = null;
            Socket socket = null;
            String str;
            List<Menu> menuList;


            try {
                serverSocket = new ServerSocket(1234);
                socket = serverSocket.accept();
                System.out.println("Server has connected!\n");
                socket.setSoTimeout(100000);

                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));


                while ((str = br.readLine()) != null) {
                    System.out.println("The message: " + str.trim());
                }


                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);


                System.out.println("Sending string ... sample data\n");
                out.println("sample data");

                out.close();
                br.close();
                socket.close();
                serverSocket.close();

            } catch(Exception e) {
            System.out.println("Whoops! It didn't work!\n : " + e.getMessage().toString());
            }
    }
}
**Please find the modified code**

package com.example.orderdish;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class MenuActivity extends Activity {

     int current = 0;
     Context ctx;
     Button vegButton, nonVegButton;
     String ip = "XXX.XXX.X.XX";           //Server IP
     int portNo = 1234;                    //Port no.

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


      ctx = getApplicationContext();

        vegButton = (Button) findViewById(R.id.btn_veg);
        nonVegButton = (Button) findViewById(R.id.btn_non_veg);



        vegButton.setOnClickListener(buttonConnectOnClickListener);
        nonVegButton.setOnClickListener(buttonConnectOnClickListener);

     }

     OnClickListener buttonConnectOnClickListener = 
       new OnClickListener(){

        @Override
        public void onClick(View view) {

         MyClientTask myClientTask = new MyClientTask(
           ip, portNo);
         myClientTask.execute();
        }};

     public class MyClientTask extends AsyncTask<Void, Void, String> {

      String dstAddress;
      int dstPort;
      String menuType;
      String response = "";
      String received_message;
      MyClientTask(String addr, int port){
       dstAddress = addr;                            //server ip
       dstPort = port;                               //server port
      }

      @Override
      protected String doInBackground(Void... arg0) {

       Socket socket = null;

       try {
        socket = new Socket(dstAddress, dstPort);

        DataOutputStream pout = new DataOutputStream(socket.getOutputStream());
        pout.writeUTF(menuType);

        DataInputStream dis = new DataInputStream(socket.getInputStream());
         received_message = DataInputStream.readUTF(dis);

          pout.close(); 


       } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        response = "UnknownHostException: " + e.toString();
       } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        response = "IOException: " + e.toString();
       } finally{
        if(socket != null){
         try {
          socket.close();
         } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
         }
        }
       }
       return received_message;
      }

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


package com.orderdish.main;


import java.io.DataInputStream;
import java.io.DataOutputStream;

import java.io.IOException;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;


public class Test {
    public final static int SOCKET_PORT = 1234; 

    public static DataInputStream dis;
    public static DataOutputStream dos;



    public static void main(String args[]) throws IOException {


        ServerSocket serverSocket = null;
        Socket socket = null;

        try {
            serverSocket = new ServerSocket(SOCKET_PORT);
            while(true) {
                System.out.println("Waiting...");
                try {
                    socket = serverSocket.accept();
                    System.out.println("Accepted connection: " + socket);

                    //Here is the change
                    dis = new DataInputStream(socket.getInputStream());
                    String received_message = DataInputStream.readUTF(dis);

                    dos = new DataOutputStream(socket.getOutputStream());
                    dos.writeUTF("sample data");

                } catch(Exception e) {
                  System.out.println("Whoops! It didn't work!\n");
                } finally {
                    if(dis != null) dis.close();
                    if(dos != null) dos.close();                    
                    if(socket != null)
                        socket.close();
                }
            } 
        } finally {
            if(serverSocket != null) serverSocket.close();
        }
    }

}

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