-1

I am trying to create an application in android that communicate(both message and file) with a Java Desktop Server.I am using Socket Programming for that. I found the code in the net.There is no error in the application when i try to run the android client it display the UI. I entered a string and click the submit button it displays "Unfortunately Application has Stopped Working" Here is my source code:

JAVA SERVER CODING:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {

    private static ServerSocket serverSocket;
    private static Socket clientSocket;
    private static InputStreamReader inputStreamReader;
    private static BufferedReader bufferedReader;
    private static String message;
    public Main(){}
    public static void main(String[] args) {

        try {
            serverSocket = new ServerSocket(7575);  //Server socket

        } catch (IOException e) {
            System.out.println("Could not listen on port: 7575");
        }

        System.out.println("Server started. Listening to the port 7575");

        while (true) {
            try {

                clientSocket = serverSocket.accept();   //accept the client connection
                inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
                bufferedReader = new BufferedReader(inputStreamReader); //get the client message
                message = bufferedReader.readLine();

                System.out.println(message);
                inputStreamReader.close();
                clientSocket.close();

            } catch (IOException ex) {
                System.out.println("Problem in message reading");
            }
        }

    }
}

Android Coding

activity_simple_client.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".SimpleClientActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="83dp"
        android:ems="10"
        android:hint="@string/clientmsg" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="46dp"
        android:text="@string/instrut"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="34dp"
        android:text="@string/send" />

    </RelativeLayout>

SimpleClientActivity.java

package com.andro.SimpleClient;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity; 
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SimpleClientActivity extends Activity {

private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button; 
private String messsage;
public SimpleClientActivity(){}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_client);
textField = (EditText) findViewById(R.id.editText1); //reference to the text field
button = (Button) findViewById(R.id.button1);   //reference to the send button

//Button press event listener
button.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

messsage = textField.getText().toString(); //get the text message on the text field
textField.setText("");      //Reset the text field to blank

try {

 client = new Socket("localhost", 7575);  //connect to server
 printwriter = new PrintWriter(client.getOutputStream(),true);
 printwriter.write(messsage);  //write the message to output stream

 printwriter.flush();
 printwriter.close();
 client.close();   //closing the connection

} catch (UnknownHostException e) {
 e.printStackTrace();
} catch (IOException e) {
 e.printStackTrace();
}
}
});

}
}

SimpleClient Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.andro.SimpleClient"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />
 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.andro.SimpleClient.SimpleClientActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
   </application>

  </manifest>

Am I need to modify any settings in Eclipse?. Anyone can helpme?? Thanks in advance

My LOCCAT File

  01-25 00:51:42.035: W/System.err(920): java.net.SocketException: socket failed: EACCES (Permission denied)
  01-25 00:51:42.035: W/System.err(920):    at libcore.io.IoBridge.socket(IoBridge.java:576)
  01-25 00:51:42.095: W/System.err(920):    at java.net.PlainSocketImpl.create(PlainSocketImpl.java:201)
  01-25 00:51:42.095: W/System.err(920):    at java.net.Socket.startupSocket(Socket.java:560)
  01-25 00:51:42.105: W/System.err(920):    at java.net.Socket.tryAllAddresses(Socket.java:128)
  01-25 00:51:42.105: W/System.err(920):    at java.net.Socket.<init>(Socket.java:178)
  01-25 00:51:42.105: W/System.err(920):    at java.net.Socket.<init>(Socket.java:150)
  01-25 00:51:42.105: W/System.err(920):    at com.android.homeapp.Sendstring.run(Sendstring.java:17)
  01-25 00:51:42.105: W/System.err(920):    at java.lang.Thread.run(Thread.java:841)
  01-25 00:51:42.105: W/System.err(920): Caused by: libcore.io.ErrnoException: socket failed: EACCES (Permission denied)
  01-25 00:51:42.105: W/System.err(920):    at libcore.io.Posix.socket(Native Method)
  01-25 00:51:42.105: W/System.err(920):    at libcore.io.BlockGuardOs.socket(BlockGuardOs.java:181)
  01-25 00:51:42.125: W/System.err(920):    at libcore.io.IoBridge.socket(IoBridge.java:561)

  I changed my Mainactivity.java as follows but it still display "Application has Stopped" and in my logcat "MainThread doing too much of work"

MainActivity.java

   package com.andro.asynctask;
   import java.io.IOException;
   import java.io.PrintWriter;
   import java.net.Socket;
   import java.net.UnknownHostException;
   import android.os.AsyncTask;
   import android.os.Bundle;
   import android.app.Activity;
   import android.view.Menu;
   import android.widget.EditText;
   import android.widget.Button;
   import android.view.*;
   public class MainActivity extends Activity {
   private String mMsg;
   private Socket client;
   private PrintWriter writer;
   private Asyncclass ac;
   private EditText txt;
   //private Button btn;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   txt=(EditText)findViewById(R.id.editText1);
   //btn=(Button)findViewById(R.id.button1);
   }


   class Asyncclass extends AsyncTask<String,Void, String> 
   {
       public Asyncclass(String msg)
       {  
        mMsg=msg;
       }
    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        try
        {
        hardtask(); 
        }

        catch(IOException i)
        {
            i.printStackTrace();
        }
        return null;
    }
     public void hardtask() throws IOException,UnknownHostException
     {
            client=new Socket("localhost", 7575);
            writer=new PrintWriter(client.getOutputStream(),true);
            writer.write(mMsg);
            writer.flush();
            writer.close();
     }
        }
   public void OnClick(View view)
   {
   mMsg=txt.getText().toString();
   ac=new Asyncclass(mMsg);
   ac.execute();
   }
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
   // Inflate the menu; this adds items to the action bar if it is present.
   getMenuInflater().inflate(R.menu.main, menu);
   return true;
   }
   }
user3172659
  • 21
  • 1
  • 3
  • Your logcat will tell you *exactly* what the problem is. – Brian Roach Jan 23 '14 at 09:38
  • Other than what @PsHegger suggested, go through [this](http://stackoverflow.com/questions/4779963/how-can-i-access-my-localhost-from-my-android-device). May be you are trying to access 127.0.0.1 instead of 10.0.2.2 – MjZac Jan 25 '14 at 06:42

2 Answers2

1

You are trying to make network communication on the main thread, which is not permitted on Android 4.0+. To solve the crash just move your code to another Thread (You should have a look at AsyncTask for example).

You can do something like that:

private class SendMessage implements Runnable {
    private String mMsg;

    public SendMessage(String msg) {
        mMsg = msg;
    }

    public void run() {
        try {

            client = new Socket("localhost", 7575);  //connect to server
            printwriter = new PrintWriter(client.getOutputStream(),true);
            printwriter.write(messsage);  //write the message to output stream

            printwriter.flush();
            printwriter.close();
            client.close();   //closing the connection

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

And then change the onClick to this:

public void onClick(View v) {
    messsage = textField.getText().toString(); //get the text message on the text field
    textField.setText("");      //Reset the text field to blank

    new Thread(new SendMessage(message)).start();      // start a new thread to make the communication in the background
}
pshegger
  • 2,526
  • 24
  • 29
  • I am very new to android pls tell me how can i do this.I try to paste in a new class it displays error – user3172659 Jan 23 '14 at 10:13
  • 1
    In the logcat it says that permission is denied, so my guess would be: you forgot to declare the Internet permission. Add this to your `AndroidManifest.xml`: `` – pshegger Jan 25 '14 at 09:24
  • Thank u for the guidance.I got the answer I change localhost to 10.0.2.2 and also Iam forget to give the permission to use the Internet. – user3172659 Jan 25 '14 at 13:02
0
java.net.SocketException: socket failed: EACCES (Permission denied)

Did you debug in Emulator?

client = new Socket("localhost", 7575);  //connect to server

Please using 10.0.0.2 and use computer IP Address if you are using Android Phone and make sure that you are connected to wifi (Can connect to computer IP)

Luc
  • 2,800
  • 2
  • 25
  • 46