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,
- I start up a server on "Simple Socket Tester" on the other phone.
- I connect the two phone using WiFi direct from my application. When connection is done "ConnectTask" runs.
- I go back to "Simple Socket Tester" on the other phone and see that the a client is connected to the server.
- 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();
}
});