1. 2015 is going to be a great year for Android! Why wait??
    Samsung Galaxy Note 5 | Samsung Galaxy S6 | HTC One M9
  2. New Forum Created: Samsung Gear VR!

android server client communication issue


  1. GaryDoo

    GaryDoo Member

    Hi,
    I'm hoping someone here can help me, I am trying to create a basic application that transmits GPS co ordinates of the device to a server. I am a complete noobie to socket programming (well, I covered the bare basics in college this year).

    As a stepping stone, I am following a tutorial, that creates the server, and the android client, it is designed to send an input from the user to the server and the server prints it on the console.
    I'm becoming quite familar with how to set up the basics of the server and the client i.e. opening ports etc. The problem with this is, when hit send, the app crashes, when tested on the emulator, there is obviously an issue, but I can't see it.

    When I test with device, and hit send, there is nothing printed to the console. I've attached both the client and server code below, the ip in the code below is for the emulator, I change this to my device ip with testing with it.

    ****SERVER****

    [HIGH]
    public class Additional_Server {
    private static ServerSocket serverSocket;
    private static Socket clientSocket;
    private static InputStreamReader inputStreamReader;
    private static BufferedReader bufferedReader;
    private static String message;

    public static void main(String[] args) {
    try {
    serverSocket = new ServerSocket(2001); // Server socket
    } catch (IOException e) {
    System.out.println("Could not listen on port: 2001");
    }
    System.out.println("Server started. Listening to the port 2001");
    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");
    }
    }
    }
    }
    [/HIGH]

    ****CLIENT****

    [HIGH]

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

    public class TCPclient extends Activity {
    private Socket client;
    private PrintWriter printwriter;
    private EditText textField;
    private Button button;
    private String messsage;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tcpclient);
    textField = (EditText) findViewById(R.id.Msg); // reference to the text field
    button = (Button) findViewById(R.id.bSend); // 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("127.0.0.1", 2001); // 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();
    }
    }
    });
    }
    }
    [/HIGH]

    I really would appreciate any help, I'm pulling my hair out here. Any specifics would be great. Thanks in advance!!!

    Advertisement
    :
  2. GaryDoo

    GaryDoo Member

    anyone???? :confused:
  3. jonbonazza

    jonbonazza Well-Known Member

    Do you have the INTERNET permission declared in your manifest?

    Can you post the log cat output?
  4. GaryDoo

    GaryDoo Member

    Hi,

    here is my manifest, I have INTERNET permission declared..I think it's done correctly?

    [HIGH]
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="gary.doolin.client"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.INTERNET" />
    <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
    android:name=".TCPclient"
    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>


    [/HIGH]


    i have to post my logcat in a seperate post as it is too large..:eek:
  5. GaryDoo

    GaryDoo Member

    Hi,

    Here's my logcat output, I've just wrapped it in tags to make it a little neater...thanks for your help

    PHP:
    01-23 20:53:16.602D/AndroidRuntime(659): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
    01-23 20:53:16.602D/AndroidRuntime(659): CheckJNI is ON
    01
    -23 20:53:17.362D/AndroidRuntime(659): Calling main entry com.android.commands.pm.Pm
    01
    -23 20:53:17.402D/AndroidRuntime(659): Shutting down VM
    01
    -23 20:53:17.422D/dalvikvm(659): GC_CONCURRENT freed 101K78free 462K/2048Kpaused 1ms+1ms
    01
    -23 20:53:17.422D/dalvikvm(659): Debugger has detachedobject registry had 1 entries
    01
    -23 20:53:17.433I/AndroidRuntime(659): NOTEattach of thread 'Binder Thread #3' failed
    01
    -23 20:53:18.022D/AndroidRuntime(672): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
    01-23 20:53:18.022D/AndroidRuntime(672): CheckJNI is ON
    01
    -23 20:53:18.752D/AndroidRuntime(672): Calling main entry com.android.commands.am.Am
    01
    -23 20:53:18.782I/ActivityManager(76): START {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHERflg=0x10000000 cmp=gary.doolin.client/.TCPclientfrom pid 672
    01
    -23 20:53:18.782W/WindowManager(76): Failure taking screenshot for (120x180to layer 21005
    01
    -23 20:53:18.822D/AndroidRuntime(672): Shutting down VM
    01
    -23 20:53:18.842D/dalvikvm(672): GC_CONCURRENT freed 102K77free 483K/2048Kpaused 1ms+2ms
    01
    -23 20:53:18.842D/dalvikvm(672): Debugger has detachedobject registry had 1 entries
    01
    -23 20:53:18.862D/dalvikvm(682): Not late-enabling CheckJNI (already on)
    01-23 20:53:18.872I/AndroidRuntime(672): NOTEattach of thread 'Binder Thread #3' failed
    01
    -23 20:53:18.902I/ActivityManager(76): Start proc gary.doolin.client for activity gary.doolin.client/.TCPclientpid=682 uid=10048 gids={3003}
    01-23 20:53:18.922I/WindowManager(76): createSurface Window{412e9590 Starting gary.doolin.client paused=false}: DRAW NOW PENDING
    01
    -23 20:53:19.102W/NetworkManagementSocketTagger(76): setKernelCountSet(100481failed with errno -2
    01
    -23 20:53:19.852I/WindowManager(76): createSurface Window{41335058 gary.doolin.client/gary.doolin.client.TCPclient paused=false}: DRAW NOW PENDING
    01
    -23 20:53:19.923D/gralloc_goldfish(682): Emulator without GPU emulation detected.
    01-23 20:53:19.962I/ActivityManager(76): Displayed gary.doolin.client/.TCPclient: +1s157ms
    01
    -23 20:53:20.202W/NetworkManagementSocketTagger(76): setKernelCountSet(100210failed with errno -2
    01
    -23 20:54:38.833D/dalvikvm(140): GC_CONCURRENT freed 1523K19free 7479K/9159Kpaused 46ms+24ms
    01
    -23 20:54:46.002D/AndroidRuntime(682): Shutting down VM
    01
    -23 20:54:46.032W/dalvikvm(682): threadid=1thread exiting with uncaught exception (group=0x409961f8)
    01-23 20:54:46.082E/AndroidRuntime(682): FATAL EXCEPTIONmain
    01
    -23 20:54:46.082E/AndroidRuntime(682): android.os.NetworkOnMainThreadException
    01
    -23 20:54:46.082E/AndroidRuntime(682):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
    01-23 20:54:46.082E/AndroidRuntime(682):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:74)
    01-23 20:54:46.082E/AndroidRuntime(682):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
    01-23 20:54:46.082E/AndroidRuntime(682):     at libcore.io.IoBridge.connect(IoBridge.java:112)
    01-23 20:54:46.082E/AndroidRuntime(682):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
    01-23 20:54:46.082E/AndroidRuntime(682):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    01-23 20:54:46.082E/AndroidRuntime(682):     at java.net.Socket.startupSocket(Socket.java:566)
    01-23 20:54:46.082E/AndroidRuntime(682):     at java.net.Socket.tryAllAddresses(Socket.java:127)
    01-23 20:54:46.082E/AndroidRuntime(682):     at java.net.Socket.<init>(Socket.java:177)
    01-23 20:54:46.082E/AndroidRuntime(682):     at java.net.Socket.<init>(Socket.java:149)
    01-23 20:54:46.082E/AndroidRuntime(682):     at gary.doolin.client.TCPclient$1.onClick(TCPclient.java:40)
    01-23 20:54:46.082E/AndroidRuntime(682):     at android.view.View.performClick(View.java:3480)
    01-23 20:54:46.082E/AndroidRuntime(682):     at android.view.View$PerformClick.run(View.java:13983)
    01-23 20:54:46.082E/AndroidRuntime(682):     at android.os.Handler.handleCallback(Handler.java:605)
    01-23 20:54:46.082E/AndroidRuntime(682):     at android.os.Handler.dispatchMessage(Handler.java:92)
    01-23 20:54:46.082E/AndroidRuntime(682):     at android.os.Looper.loop(Looper.java:137)
    01-23 20:54:46.082E/AndroidRuntime(682):     at android.app.ActivityThread.main(ActivityThread.java:4340)
    01-23 20:54:46.082E/AndroidRuntime(682):     at java.lang.reflect.Method.invokeNative(Native Method)
    01-23 20:54:46.082E/AndroidRuntime(682):     at java.lang.reflect.Method.invoke(Method.java:511)
    01-23 20:54:46.082E/AndroidRuntime(682):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    01-23 20:54:46.082E/AndroidRuntime(682):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    01-23 20:54:46.082E/AndroidRuntime(682):     at dalvik.system.NativeStart.main(Native Method)
    01-23 20:54:46.152W/ActivityManager(76):   Force finishing activity gary.doolin.client/.TCPclient
    01
    -23 20:54:46.152W/WindowManager(76): Failure taking screenshot for (120x180to layer 21010
    01
    -23 20:54:46.272I/WindowManager(76): createSurface Window{4134b258  paused=false}: DRAW NOW PENDING
    01
    -23 20:54:46.736W/ActivityManager(76): Activity pause timeout for ActivityRecord{4134cba0 gary.doolin.client/.TCPclient}
    01-23 20:54:46.772W/NetworkManagementSocketTagger(76): setKernelCountSet(100211failed with errno -2
    01
    -23 20:54:46.802I/WindowManager(76): createSurface Window{411e5d30 com.android.launcher/com.android.launcher2.Launcher paused=false}: DRAW NOW PENDING
    01
    -23 20:54:47.423W/NetworkManagementSocketTagger(76): setKernelCountSet(100480failed with errno -2
    01
    -23 20:54:49.762I/Process(682): Sending signalPID682 SIG9
    01
    -23 20:54:49.792I/ActivityManager(76): Process gary.doolin.client (pid 682has died.
    01-23 20:54:49.792I/WindowManager(76): WIN DEATHWindow{41335058 gary.doolin.client/gary.doolin.client.TCPclient paused=false}
    01-23 20:54:49.912W/InputManagerService(76): Got RemoteException sending setActive(falsenotification to pid 682 uid 10048
    01
    -23 20:54:50.402D/dalvikvm(140): GC_CONCURRENT freed 394K19free 7492K/9159Kpaused 4ms+4ms
    01
    -23 20:54:57.523W/ActivityManager(76): Activity destroy timeout for ActivityRecord{4134cba0 gary.doolin.client/.TCPclient}
  6. jonbonazza

    jonbonazza Well-Known Member

    Okay, so i looked at your code again, and the problem is that after you accept the connection on the server, you immediately try to read from the buffer. At this point, all kinds of async issues could be happening. First, i would begin by removing all messageing code and make sure the client is actually able to connect to the server. Throw in some logging lines on both server and client and see what you find.

    After you know that is working, i would then make your server construct a new thread that will listen for incoming messages in an infinite loop. This way the message passing is asyncronous and the server can continue to listen for new connections.
  7. GaryDoo

    GaryDoo Member

    @jonbonazza

    I tried two things, one, I tried to put my socket code within an async task, this didn't seem to work for me.

    2. I tried to strip it back, I just have a simple server client which I have posted below.

    SERVER

    [HIGH]
    public class Additional_Server {

    private static String message;

    public static void main(String[] args) throws Exception {


    Socket s;
    ServerSocket ss = new ServerSocket(2001);


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



    while (true) {
    try {
    System.out.println("Server: waiting for connection ..");

    s = ss.accept();
    InputStream in = s.getInputStream();
    Scanner r = new Scanner(in);
    OutputStream o = s.getOutputStream();
    PrintWriter p = new PrintWriter(o);

    String inputLine;
    inputLine = r.nextLine();
    p.println("Hello " + inputLine + " from Gary");
    p.close();



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

    }
    }[/HIGH]

    CLIENT

    [HIGH]import java.io.IOException;
    import java.io.InputStream;
    import java.io_OutputStream;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.Scanner;
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;

    public class MainActivity extends Activity {

    private Socket s;
    private PrintWriter p;
    TextView display;
    Button test;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    test = (Button) findViewById(R.id.test);
    display = (TextView) findViewById(R.id.Sdisplay);

    test.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
    // TODO Auto-generated method stub

    try {
    s = new Socket("192.168.1.*", 2001); // connect to server
    OutputStream o = s.getOutputStream();
    PrintWriter p = new PrintWriter(o);
    InputStream in = s.getInputStream();
    Scanner r = new Scanner(in);

    p.println("Gary");
    p.flush();


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

    }
    }[/HIGH]

    I'm just trying to get the printout to the console, but nothing is happening. I'm trying to do a project on this for college, we haven't done android programming or socket programming before...

    What really bothers me here is that it looks right and I can't seem to see what the issue is.

    I really would appreciate some of your thoughts or even what you might do in this situation?

    I have been stuck on this hurdle for weeks now, and normally I don't mind plugging away, but time is running out for me...:(

    Regards,

    Gary
Loading...

Share This Page