1

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 bear 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();
        }
    }
}
2
  • 1
    what is the code of your Server? What crashes exactly ? The server or the client? Commented Sep 3, 2016 at 11:10
  • 1
    The client/android app crashes. @NicolasFilotto Commented Sep 3, 2016 at 11:14

3 Answers 3

1

As requested an extended 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> {
public static PrintWriter out;
BufferedReader in;
public static boolean running = true;
    @Override
    protected String doInBackground(String... message) {

        try
        {
            InetAddress serverAddr = InetAddress.getByName("localhost");
            Socket socket = new Socket(serverAddr, 8008);
            // send the message to the server
            out = new PrintWriter(new BufferedWriter(
                              new OutputStreamWriter(socket.getOutputStream())), true);

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

        while(running) {
            String msgfromserver = in.readLine();
        }
        }
        catch (Exception e)
        {}

        return null;
    }

    public static void sendmsg(String msg){
        if(out!=null){
            out.println(msg);
            out.flush();
        }
    }
}

Usage: Call connection.sendmsg("some text"); from OnClick method of button

And set connection.running = false; onbackpress. (Or before finishing activity)

Sign up to request clarification or add additional context in comments.

1 Comment

One problem, when adding the connection.sendmsg("some text") the editor gives error and tells met to make sendmsg static. How do I fix this? Error: Error:(22, 19) error: non-static method sendmsg(String) cannot be referenced from a static context
1

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.

4 Comments

Can you please give me an example? @user6657161
Wait i am coding an example for you.
Thanks @user6657161
Thanks, the example works. Could you maybe just show me how I could send a message to the server each time a button is pressed without closing and opening the server each time.
1

Two changes in code. public static void sendmsg and public public static PrintWriter out at begining of AsyncTask class

2 Comments

Added it as answer by mistake.
I can't delete my answer as i am on android. Alas!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.