I did a TCP client on Java and works fine, but when I import the class to my Android project, it doesn't work.
Android code:
// ...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.SEND);
ssid = (EditText) findViewById(R.id.textSsid);
pass = (EditText) findViewById(R.id.textPass);
debugText = (EditText) findViewById(R.id.debugText);
cliente = new ClienteTCP();
debugText.setText("Version 1-prealpha");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
demo(v);
}
});
}
public void demo(View view) {
cliente.configure(ssid.getText(), pass.getText());
CharSequence cs = cliente.sendMessage("Hola Mundo");
if ( cs != null)
debugText.setText(cs);
else
debugText.setText("ERROR OCURRED");
}
// ...
I always get the "ERROR OCURRED" message, I try to use another IPs, but all of them works fine on Java and not on android.
The class code:
private CharSequence SSID, pass;
private String HOST = "52.28.45.92"; // My external server i tried with localhot server too ...
// of course i have a server aplication running hahaha
private int PORT = 5000;
private Socket s;
private DataOutputStream oms;
// ...
public CharSequence sendMessage(String ms) {
DataInputStream ims;
CharSequence data = null;
try {
s = new Socket(HOST,PORT);
oms = new DataOutputStream(s.getOutputStream());
ims = new DataInputStream(s.getInputStream());
oms.writeUTF(ms+getFull());
data = ims.readUTF();
oms.close();
ims.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
I think it can be due to my emulator, any ideas? is the code wrong?
EDIT: Server code:
# ...
# Wrote on Python:
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print "received data:", data
conn.send(data+'\r\n')
conn.close()
asked Apr 23, 2015 at 19:56
Josete Manu
1872 silver badges17 bronze badges
lang-java
public void demo(View view)on different thread than Main. 2 Can you post log error?DataInputStreamreadUTF()method is not the same asreadLine(), here are more details the data that your Python program sends can't be read using thereadUTF()method.catch (IOException e). So you are already printing the stack trace but you could also log e.getMessage() to see the reason of the exception. Or return e.getMessage() there to see it directly.