Am new to android and i have an issue with socket programming.
class ClientAsycTask extends AsyncTask<String,Void,String>{
ProgressDialog progress;
@Override
protected void onPreExecute() {
progress = new ProgressDialog(MainActivity.this);
progress.setMessage("Connection Server Please wait");
progress.setIndeterminate(true);
progress.show();
}
@Override
protected String doInBackground(String... params) {
String result = null;
Socket socket = new Socket();
String host = "systemteq.gotdns.com";
Integer port = 4999;
DataOutputStream s_out = null;
BufferedReader s_in = null;
try{
socket.connect(new InetSocketAddress(host, port));
s_out = new DataOutputStream( socket.getOutputStream());
s_in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
byte[] messages = new byte[]{0x10,0x01,0x03,0x00,0x00};
s_out.write(messages);
String response;
while((response = s_in.readLine())!=null){
result += response;
}
//result = "Successfully"+s_in.read();//s_in.readLine();
socket.close();
}catch (Exception e){
Toast.makeText(MainActivity.this,"systemteq.gotdns.com:4999 not connected",Toast.LENGTH_SHORT).show();
}
return result;
}
@Override
protected void onPostExecute(String s) {
if(progress.isShowing()){
progress.dismiss();
}
Toast.makeText(MainActivity.this,"Connected "+s,Toast.LENGTH_SHORT).show();
tv.setText(s);
}
}
Above code sends a hexadecimal code to server and server responds with some hexadecimal code, lets say 10 01 20 10 00.[five bytes].
But when i run above code progress dialog never close. after working around i found that s_in.readLine() has some issue reading the response from server.
I have went through lots of links but i was not successful while solving this issue. Kindly help me to crack this.
UPDATE:-
After using DataInputStream:-
s_in = new DataInputStream(socket.getInputStream());
byte[] messages = new byte[]{0x10,0x01,0x03,0x00,0x00};
s_out.write(messages);
String response;
System.out.println("START");
result = s_in.readUTF();
It still does not take response byte. Though request is successful.
Update 2
byte m = s_in.readByte();
result = Byte.toString(m);
Now am getting byte value but i should get 5 bytes , instead of getting 5 bytes am getting only one. Please help me with this thing
If you are waiting for binary data, do not use InputStreamReader
, try DataInputStream
instead.
The readLine()
waits for '\\n', '\\r', "\\r\\n" or the end of the reader.
UPDATE: if you know exact number of bytes, read them into array.
byte[] buf = new byte[5];
s_in.read(buf);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.