Android : Asynctask android won't write to socket

on Saturday, September 27, 2014


Hey I was trying to debugg another app, that uses Asynctasks with a bit more complicated logic to send and recieve lines from a server. In this app, I created a simple Asynctask class that creates a socket, connects to an ip on a port and sends a line. The server is written in python using the Twisted module, so the encoding is set to UTF-8. When the socket is initialised on the device a TCP handshake is done successfuly though a bit oddly (Syn,ack -> ack-> fin,ack) after the initialisation I get the input and output streams which seem to have been rendered useless, though I can write and read from them, nothing ever leaves the device (checked with wireshark). Anyone has had this problem and can help me solve it?


-----> Activity with Task code <--------



public class MyActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
network task = new network();
task.execute();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

private class network extends AsyncTask<Void, Integer, Void>{

@Override
protected Void doInBackground(Void... voids) {
Socket s = null;
PrintWriter out = null;
DataInputStream in = null;
InetAddress addr = null;
int port = 2222;
String ip = new String("192.162.1.109");
try{
addr = InetAddress.getByName(ip);}
catch (UnknownHostException e){
e.printStackTrace();
}
try{
s = new Socket(addr, port);}
catch (IOException e){
e.printStackTrace();
}
try{
in = new DataInputStream(s.getInputStream());
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream(), "UTF-8")),
true);
out.println("100\n");
out.flush();
}catch (IOException e){
e.printStackTrace();
}
try{
in.close();
out.close();
s.close();}catch (IOException e){
e.printStackTrace();
}
return null;
}
}
}

0 comments:

Post a Comment