I’m trying to test a very simple 2 way IM app. With the client being on the android and the server on my PC(java). I have tested this app in java from PC to PC and it works correctly.
But on my android emulator, when I send a message over to my android emulator from my PC, the message is displayed on my android only when it is sent twice from my PC. Clicking the send button once from the PC, nothing shows, clicking it again the message then shows on the android.
I am thinking there is something wrong with my runnable method but I am not entirely sure, I hope someone can point out the issue. Thanks in advance.
static Socket kkSocket = null;
static PrintWriter out = null;
static BufferedReader in = null;
static String msg;
TextView tv;
EditText et;
Handler mHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv_message);
et = (EditText) findViewById(R.id.et_message);
Button btnSend = (Button) findViewById(R.id.btn_send);
btnSend .setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
out.println(et.getText());
}
});
Thread t = new Thread() {
public void run() {
processThread();
}
};
t.start();
}
private void processThread() {
try {
kkSocket = new Socket("xxx.xx.xx.xxx", 4444);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out = new PrintWriter(kkSocket.getOutputStream(), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while (in.readLine() != null)
{
msg = in.readLine();
mHandler.post(mUpdateResults);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Runnable mUpdateResults = new Runnable() {
public void run() {
tv.setText("Server: " + msg);
}
};
Is a newline character being sent after every message?
The buffered reader may be blocking waiting for a newline char.