1

I am connecting my phone to a sensor via WiFi direct. I am supposed to connect to port 5001 for sensor data. I have been having trouble setting up the TCP client so I can open the port and retrieve data. I found this post Really simple TCP client which I copy pasted the code from.

To test my code i use the app "Simple Socket Tester" where i start a server with IP address 192.168.1.52, port 5001 on another phone. I connect my phone via WiFi direct, after successfull connection the ConnectTask code should run. But i get "java.net.ConnectException: failed to connect to /192.168.1.52 (port 5001): connect failed: ETIMEDOUT (Connection timed out)". Why could this be? What am I doing wrong?.

EDIT:

I managed to connect to the server now. But now I am not able to see the messages that I am sending from the server.

Here is a detailed walkthrough on what I am doing,

  1. I start up a server on "Simple Socket Tester" on the other phone.
  2. I connect the two phone using WiFi direct from my application. When connection is done "ConnectTask" runs.
  3. I go back to "Simple Socket Tester" on the other phone and see that the a client is connected to the server.
    1. I send a message from the server, but can not see the message on the client side. How can I display the message sent by the server?

My TCP Client code:

public class TCPClient {
public static final String SERVER_IP = "192.168.1.52"; //your computer IP address
public static final int SERVER_PORT = 5001;
// message to send to the server
private String mServerMessage;
// sends message received notifications
private OnMessageReceived mMessageListener = null;
// while this is true, the server will continue running
private boolean mRun = false;
// used to send messages
private PrintWriter mBufferOut;
// used to read messages from the server
private BufferedReader mBufferIn;

/**
 * Constructor of the class. OnMessagedReceived listens for the messages received from server
 */
public TCPClient(OnMessageReceived listener) {
    mMessageListener = listener;
}

/**
 * Sends the message entered by client to the server
 *
 * @param message text entered by client
 */
public void sendMessage(String message) {
    if (mBufferOut != null && !mBufferOut.checkError()) {
        mBufferOut.println(message);
        mBufferOut.flush();
    }
}

/**
 * Close the connection and release the members
 */
public void stopClient() {
    Log.i("Debug", "stopClient");

    // send mesage that we are closing the connection
    //sendMessage(Constants.CLOSED_CONNECTION + "Kazy");

    mRun = false;

    if (mBufferOut != null) {
        mBufferOut.flush();
        mBufferOut.close();
    }

    mMessageListener = null;
    mBufferIn = null;
    mBufferOut = null;
    mServerMessage = null;
}

public void run() {

    mRun = true;

    try {
        //here you must put your computer's IP address.
        InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

        Log.e("TCP Client", "C: Connecting...");

        //create a socket to make the connection with the server
        Socket socket = new Socket(serverAddr, SERVER_PORT);

        try {
            Log.i("Debug", "inside try catch");
            //sends the message to the server
            mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

            //receives the message which the server sends back
            mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            // send login name
            //sendMessage(Constants.LOGIN_NAME + PreferencesManager.getInstance().getUserName());
            //sendMessage("Hi");
            //in this while the client listens for the messages sent by the server
            while (mRun) {
                mServerMessage = mBufferIn.readLine();
                if (mServerMessage != null && mMessageListener != null) {
                    //call the method messageReceived from MyActivity class
                    mMessageListener.messageReceived(mServerMessage);
                }

            }
            Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");


        } catch (Exception e) {

            Log.e("TCP", "S: Error", e);

        } finally {
            //the socket must be closed. It is not possible to reconnect to this socket
            // after it is closed, which means a new socket instance has to be created.
            socket.close();
        }

    } catch (Exception e) {

        Log.e("TCP", "C: Error", e);

    }

}

My ConnectTask

public class ConnectTask extends AsyncTask<String, String, TCPClient> {

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

    //we create a TCPClient object
    TCPClient mTCPClient = new TCPClient(new TCPClient.OnMessageReceived() {
        @Override
        //here the messageReceived method is implemented
        public void messageReceived(String message) {
            //this method calls the onProgressUpdate
            publishProgress(message);
        }
    });
    mTCPClient.run();

    return null;
}

@Override
protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);
    //response received from server
    Log.d("test", "response " + values[0]);
    //process server response here....

}
}

The part in my WiFi direct activity that starts the ConnectTask

public class WiFiDirectActivity extends Activity implements WifiP2pManager.ChannelListener, DeviceListFragment.DeviceActionListener {
...

    @Override
public void connect(WifiP2pConfig config) {
    config.groupOwnerIntent = 0;
    manager.connect(channel, config, new WifiP2pManager.ActionListener()
    {

        @Override
        public void onSuccess() {
            // WiFiDirectBroadcastReceiver will notify us. Ignore for now.
            new ConnectTask().execute("");
            //sends the message to the server
            if (mTCPClient != null) {
                mTCPClient.sendMessage("testing");
            }

        }

        @Override
        public void onFailure(int reason) {
            Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
                    Toast.LENGTH_SHORT).show();
        }
    });
Community
  • 1
  • 1
Kspr
  • 665
  • 7
  • 19
  • Are you running in debug mode...?? – Hema Apr 08 '17 at 10:41
  • `am supposed to listen to port 5001 for sensor data`. Server sockets listen for client connections. So do not confuse us with using listening differently. I think your client has to connect to port 5001 and then reads incoming data from the socket. – greenapps Apr 08 '17 at 10:47
  • @Hema No I am not, but I manage to connect to the server maybe every 5th time. It is weird, – Kspr Apr 08 '17 at 10:51
  • @greenapps do you have any suggestions on how to do that instead? – Kspr Apr 08 '17 at 10:51
  • To do what instead? – greenapps Apr 08 '17 at 10:53
  • @greenapps To get the client to connect to port 5001, sorry I am a bit confused at the moment.. or I mean, I thought I already was trying to do that? Did you mean I phrased the question wrong? – Kspr Apr 08 '17 at 10:55
  • Yes. You used the word 'listen' in a confusing way. So you use one phone as hotspot? If so then edit your post and tell direct!y which one. – greenapps Apr 08 '17 at 10:57
  • @greenapps Right, edited it now. Thanks – Kspr Apr 08 '17 at 11:00
  • I managed to connect to the server now. But now instead I can't retrieve the messages I send from the server on the client. Nothing happens. Any ideas why? – Kspr Apr 08 '17 at 11:02
  • @greenapps I am sorry, I updated the post now. Is it still unclear? I am using WiFi direct. – Kspr Apr 08 '17 at 11:07

0 Answers0