Android : Qt Server/Android Client. Get Data from server though TCP connection

on Thursday, April 16, 2015


I have my server class set up in Qt creator, and an Android application that connects to the server and is supposed to retrieve data from it. I already managed to set up a TCP connection between the two, like this:



public class SplashScreen extends Activity{
private static int SPLASH_TIME_OUT = 3000;
private Socket s;
TextView testText ;

Button startConnection ;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

startConnection = (Button) findViewById(R.id.connect);
testText = (TextView) findViewById(R.id.textView14) ;

//on click of the button, the client setup code will be called
startConnection.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
try{new AsyncAction().execute();}
catch (Exception e) {e.printStackTrace();}
}
});

}

private class AsyncAction extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {}

@Override
protected Void doInBackground(Void... params)
{
GlobalData.establishTcpConnection () ;

return null;//returns what you want to pass to the onPostExecute()
}

@Override
protected void onPostExecute(Void result)
{
//if connection established, calls onPostExecute, and moves onto new activity
super.onPostExecute(result);
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(intent);
}
}
}


I use AsyncTask to handle the connection. In my doInBackground, I call a static method from another class that establishes the connection. Once the connection is established, the user will be able to access the rest of the app, as the intent to go to the next Activity is called in the onPostExecute.


My problem is that I have no idea how to retrieve and pass back and forth data between the Qt server and my android app. Here is the code for sending data in qt:



void tcpServer::sendDataToClient(quint16 token)
{
if (socketConnected==false)
{
return;
}

QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
QString text;

out << (quint16)0;
out << token;
if (token==TOKEN_SERVER_DESIGNUI)
{
text = "Laurent Zanoni";
out << text;
}

out.device()->seek(0);
out << (quint16)(block.size() - sizeof(quint16));

socket->write(block);
}


I'm very very new to Qt and havent dealt with C++ in a long while. How do I pass back and forth Strings and ints in my tcp connection?? I am at a complete loss here, any help is appreciated, thank you.


0 comments:

Post a Comment