Simon Erasmus Simon Erasmus - 3 months ago 8
Android Question

TCP from android to PC not working using java

I am trying to send a simple message over

TCP
from my android phone (using java application) to my computer. I have an socket that is listening on my computer but as soon as I run this app, it crashes. I am really new to Android developing so please bare with me...

Here is my Java code:

package com.scorekeep.clienttcp;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
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;
import android.widget.TextView;


public class MainActivity extends Activity {

EditText textOut;


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

Socket socket = null;
try {
socket = new Socket("10.0.0.10",5000);
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DOS.writeUTF("HELLO_WORLD");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Answer

You cannot execute background tasks like socket connection in ui thread. You should use AsyncTask.

Example

import android.app.*;
import android.os.*;
import android.util.*;
import java.io.*;
import java.net.*;

public class MainActivity extends Activity 
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        new connection().execute();
    }
}

class connection extends AsyncTask<String,String,String> {

    @Override
    protected String doInBackground(String... message) {

        try
        {
            InetAddress serverAddr = InetAddress.getByName("ip here");
            Socket socket = new Socket(serverAddr, 5000); //port here
    // send the message to the server
        PrintWriter out = new PrintWriter(new BufferedWriter(
                              new OutputStreamWriter(socket.getOutputStream())), true);
        out.println("hi");
        out.flush(); //optional
        socket.close();
        }
        catch (Exception e)
        {}

        return null;
    }
}

Note Untested. May contain errors.

Comments