Juan
Juan

Reputation: 9

Android Socket error with no message

I create a simple network-testing application. But It doesn't work and always throw error at Socket(). I tried to check error message by using getMessage(), there was no message printed. What should I do?

public static void main(String args[]){
    ServerSocket serverSocket = null;
    Socket socket = null;
    try{
        serverSocket = new ServerSocket(14100);
        socket = serverSocket.accept();
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
        byte[] arr = new byte[100];
        in.read(arr);
        System.out.println(new String(arr));
        String str = "Hello Client";
        out.write(str.getBytes());
    }
    catch(Exception e){
        System.out.println(e.getMessage());
    }
    finally{
        try{
            socket.close();
        }
        catch(Exception ignored){}
        try{
            serverSocket.close();
        }
        catch(Exception ignored){}
    }
}

Below is android code for Client.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    TextView tv = (TextView) findViewById(R.id.id_tv);

    Socket socket = null;
    try{
        socket = new Socket("192.168.0.52",14100);
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
        String str = "Hello Server";
        out.write(str.getBytes());
        byte arr[] = new byte[100];
        in.read(arr);
        tv.setText(new String(arr));
    }
    catch(UnknownHostException uhe){
    }
    catch(IOException ioe){
    }
    catch(Exception e){
    }
    finally{
        try{
            socket.close();
        }
        catch(Exception ignored){
        }
    }
}

Of course, I added permisson for android in AndroidManifest.xml

Upvotes: 0

Views: 510

Answers (1)

ashoke
ashoke

Reputation: 6461

Move the socket code out of UI main thread onCreate() to an AsyncTask or a regular thread.

For a quick test, wrap all your socket code into a thread like so:

    new Thread() { 
        public void run() {
            // Move your socket code here for a quick test
        }
    }.start();

Upvotes: 1

Related Questions