Lukas5060
Lukas5060

Reputation: 47

Android Socket Client didn't send and closes itself

I am pretty new to android and java programming and I need your help. I want to create an Android client and a server on my PC (Windows 7). I checked with putty (a program which imitates a client (without programming mistakes^^)) whether my server is programmed without mistakes. Thereby I recognized that my server is programmed correctly.

Here you can see my well-working server:

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

  ServerSocket serverSocket = null;

  try {
      serverSocket = new ServerSocket(4449);
      System.out.println("Listening on port: 4449");
  } catch (IOException e){
      System.err.println("Could not listen on port 4449.");
      System.exit(1);
  }

  Socket clientSocket = null;

  try {
      clientSocket = serverSocket.accept();
   System.out.println("Got connection.");
  } catch (IOException e) {
      System.err.println("Accept failed: 4449.");
      System.exit(1);
  }

  BufferedReader in = null;
  PrintWriter out = null;
  try {
      in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

      out = new PrintWriter(clientSocket.getOutputStream(), true);
  } catch (IOException e) {
      System.err.println("Read failed");
      e.printStackTrace();
  }


  try {

      System.out.println("message: " + in.readLine());
      out.println("hab was bekommen!");
  } catch (IOException e) {
      System.err.println("Can't get a message from Client.");
      e.printStackTrace();

  }
  }
  }

I also tried to create an Android client for this server, but i didn't managed it.

Here is my Mainactivity:

public class AndroidClient extends Activity {

EditText textOut;
TextView textIn;
TextView problems;

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

    textOut = (EditText)findViewById(R.id.textout);
    Button buttonSend = (Button)findViewById(R.id.send);
    textIn = (TextView)findViewById(R.id.textin);
    problems = (TextView)findViewById(R.id.problems);
    buttonSend.setOnClickListener(buttonSendOnClickListener);
}

Button.OnClickListener buttonSendOnClickListener 
= new Button.OnClickListener() {


    @Override
    public void onClick(View arg0) {
        //TODO Auto-generated method stub
        Socket client = null;


        BufferedReader in = null;
        PrintWriter out = null;

        try {
            client = new Socket("192.168.2.107", 4449);
            in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            out = new PrintWriter(client.getOutputStream(), true);
        } catch (UnknownHostException e) {
            problems.setText("Unknown host: 192.168.2.107");
        } catch (IOException e) {
            // System.out.println("No Input/Output.");
            problems.setText("No Input/Output.");
        }

        try {
            out.println("Hallo.");
            textIn.setText(in.readLine());
        } catch (IOException e) {
            problems.setText("Can't send/ get message.");
        }
    }   
};



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_android_client, menu);
    return true;
}
    }

So far so good. When i start my app on my android smartphone the app starts without any problem. Then i type something in my EditText field 'textOut' und pushed to 'Send' button. Then my screen gets black and the app closes itself. I also pasted the permission in the AndroidManifest.xml to enter the internet and to use access Wifi.

I hope that someone can help me, because i am working on this problem for 2 days and haven't found any solution yet. I mainly used this side (http://android-er.blogspot.de/2011/01/simple-communication-using.html) and of course some other sides, but there i got most information. Furthermore there are no shown mistakes in my source code.

With kind regards,

Lukas5060

edit: Here is my LogCat:

12-28 20:21:55.929: I/dalvikvm(698): threadid=3: reacting to signal 3 12-28 20:21:56.039: I/dalvikvm(698): Wrote stack traces to '/data/anr/traces.txt' 12-28 20:21:56.259: I/dalvikvm(698): threadid=3: reacting to signal 3 12-28 20:21:56.299: I/dalvikvm(698): Wrote stack traces to '/data/anr/traces.txt' 12-28 20:21:56.741: D/gralloc_goldfish(698): Emulator without GPU emulation detected. 12-28 20:21:56.771: I/dalvikvm(698): threadid=3: reacting to signal 3 12-28 20:21:56.789: I/dalvikvm(698): Wrote stack traces to '/data/anr/traces.txt' 12-28 20:23:58.430: D/AndroidRuntime(698): Shutting down VM 12-28 20:23:58.430: W/dalvikvm(698): threadid=1: thread exiting with uncaught exception (group=0x409c01f8) 12-28 20:23:58.470: E/AndroidRuntime(698): FATAL EXCEPTION: main 12-28 20:23:58.470: E/AndroidRuntime(698): android.os.NetworkOnMainThreadException 12-28 20:23:58.470: E/AndroidRuntime(698): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099) 12-28 20:23:58.470: E/AndroidRuntime(698): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) 12-28 20:23:58.470: E/AndroidRuntime(698): at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 12-28 20:23:58.470: E/AndroidRuntime(698): at libcore.io.IoBridge.connect(IoBridge.java:112) 12-28 20:23:58.470: E/AndroidRuntime(698): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 12-28 20:23:58.470: E/AndroidRuntime(698): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) 12-28 20:23:58.470: E/AndroidRuntime(698): at java.net.Socket.startupSocket(Socket.java:566) 12-28 20:23:58.470: E/AndroidRuntime(698): at java.net.Socket.tryAllAddresses(Socket.java:127) 12-28 20:23:58.470: E/AndroidRuntime(698): at java.net.Socket.(Socket.java:177) 12-28 20:23:58.470: E/AndroidRuntime(698): at java.net.Socket.(Socket.java:149) 12-28 20:23:58.470: E/AndroidRuntime(698): at net.ibasic.AndroidClient$1.onClick(AndroidClient.java:50) 12-28 20:23:58.470: E/AndroidRuntime(698): at android.view.View.performClick(View.java:3511) 12-28 20:23:58.470: E/AndroidRuntime(698): at android.view.View$PerformClick.run(View.java:14105) 12-28 20:23:58.470: E/AndroidRuntime(698): at android.os.Handler.handleCallback(Handler.java:605) 12-28 20:23:58.470: E/AndroidRuntime(698): at android.os.Handler.dispatchMessage(Handler.java:92) 12-28 20:23:58.470: E/AndroidRuntime(698): at android.os.Looper.loop(Looper.java:137) 12-28 20:23:58.470: E/AndroidRuntime(698): at android.app.ActivityThread.main(ActivityThread.java:4424) 12-28 20:23:58.470: E/AndroidRuntime(698): at java.lang.reflect.Method.invokeNative(Native Method) 12-28 20:23:58.470: E/AndroidRuntime(698): at java.lang.reflect.Method.invoke(Method.java:511) 12-28 20:23:58.470: E/AndroidRuntime(698): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 12-28 20:23:58.470: E/AndroidRuntime(698): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 12-28 20:23:58.470: E/AndroidRuntime(698): at dalvik.system.NativeStart.main(Native Method) 12-28 20:23:59.070: I/dalvikvm(698): threadid=3: reacting to signal 3 12-28 20:23:59.100: I/dalvikvm(698): Wrote stack traces to '/data/anr/traces.txt' 12-28 20:24:02.420: I/Process(698): Sending signal. PID: 698 SIG: 9

Upvotes: 1

Views: 619

Answers (1)

Daniel Figueroa
Daniel Figueroa

Reputation: 10666

Okay my guess is that the problem is that your doing this in the main ui thread which is far from recommended. Instead what you should do is checkout AsyncTask which is the preferred way of doing this kind of operations (reading from files or web and a bunch of other stuff).

This is easier than it sounds what you need to do is something like this (note this is just to give you a feeling about how it looks):

private class CreateSocketTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {
        //Do the socket stuff here...
    }

    @Override
    protected void onPostExecute(String result) {
        //This is called when doInBackground has finished
        //From here you'd call a method in the main ui class.
    }
}

Heres the android doc

There are a bunch of tutorials on the net so you'll be up and running in no time.

Upvotes: 1

Related Questions