How can I receive to socket input as hexadecimal? - java

I sent a GET message with socket. And I received response message as string. But I want to receive as hexadecimal. But I didn't accomplish. This is my code block as string. Can you help me ?
dos = new DataOutputStream(socket.getOutputStream());
dis = new BufferedReader(new InputStreamReader(socket.getInputStream()));
dos.write(requestMessage.getBytes());
String data = "";
StringBuilder sb = new StringBuilder();
while ((data = dis.readLine()) != null) {
sb.append(data);
}

when you use BufferedReader you'll get the input into String format..so better way to use InputStream...
here is sample code to achieve this.
InputStream in = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] read = new byte[1024];
int len;
while((len = in.read(read)) > -1) {
baos.write(read, 0, len);
}
// this is the final byte array which contains the data
// read from Socket
byte[] bytes = baos.toByteArray();
after getting the byte[] you can convert it to hex string using the following function
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X ", b));
}
System.out.println(sb.toString());// here sb is hexadecimal string
reference from java-code-to-convert-byte-to-hexadecimal

Related

Not retriving data from socket java

i'm writing a java program that sends and receives data from a printer, i can get the command but i can't read in any way a response.
Socket s = new Socket(ip, port);
System.out.println("-----------------> MioSocket closed: "+s.isClosed());
OutputStream out = s.getOutputStream();
System.out.println("-----------------> InputStream: "+out.toString());
DataOutputStream output = new DataOutputStream(out);
String str = "GST\r";
output.writeUTF(str);
System.out.println("---->");
InputStream input = s.getInputStream();
System.out.println("-----------------> InputStream: "+input.toString());
InputStreamReader reader = new InputStreamReader(input);
System.out.println("-----------------> InputStream: "+reader.toString());
int character;
StringBuilder data = new StringBuilder();
System.out.println(reader.read());
while ((character = reader.read()) != -1) {
data.append((char) character);
}
System.out.println(data);
s.close();

Android Socket continue reading till a specific String sequence

I want to read from a socket till a specific String sequence like <END>. The problem is the server sometimes returns me the data in chunks that is when the text (JSON) is too long to be sent in packets. I want to make a logic where the socket keeps appending a String Builder until the stream ends at <END> and after that continue appending another message.
InputStreamReader inr = new InputStreamReader(socket.getInputStream());
BufferedReader br = new BufferedReader(inr);
byte[] resultBuff = new byte[0];
byte[] buff = new byte[99999];
int k;
StringBuilder sb = new StringBuilder();
while ((k = in .read(buff, 0, buff.length)) > -1) {
byte[] tbuff = new byte[resultBuff.length + k]; // temp buffer size = bytes already read + bytes last read
System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); // copy previous bytes
System.arraycopy(buff, 0, tbuff, resultBuff.length, k); // copy current lot
resultBuff = tbuff; // call the temp buffer as your result buff
System.out.println(resultBuff.length + " bytes read.");
String s = new String(resultBuff);
sb.append(s);
if (s.endsWith(DELIMITER)) {
String response = sb.toString().replace(DELIMITER, "").replace("\n", "").replace("\r", "");
System.out.println(response);
if (listener != null) {
listener.onMessageReceived(params[0], response);
} else {
Log.e(TAG, "Response :: listener.onMessageReceived null ");
}
resultBuff = new byte[0];
sb = new StringBuilder();
} else {
sb.append(s);
}
}
The goal here is to keep the while loop running so that the socket can keep reading whenever something comes in stream.
You can do something like this.
String str = "";
byte[] b = new byte[1024];
for(int r = 0; (r = is.read(b))!=-1;){
str += new String(b,0,r);
if(str.contains(DELIMITER)){
String message = str.substring(0,str.indexOf(DELIMITER));
str = str.substring(str.indexOf(DELIMITER)+DELIMITER.length());
//process message.
}
}
if(!str.isEmpty()){
//the JSON object was sent in a single chunk, porcess it
}
What this does is to store all the data read from the InputStream into the str String and when the str contains the DELIMITER it will extract the message from the str so it can be processed. This will fail if the buffer contains more then one message. You can use String[] messages = str.split(DELIMITER) to deal with that.
A better solution will be to use a Scanner, here is an example:
Scanner sc = new Scanner(in);
sc.useDelimiter(DELIMITER);
while(sc.hasNext()){
String message = sc.next();
// process message.
}

how to write encoded stream in JSON and retrieve back in ajax?

I am geeting image in input stream and encoding it into base64 and sending it to client using JSON
Following is code snippet.
Server side :
JsonObject myObj = new JsonObject();
StringBuilder responseStrBuilder = new StringBuilder();
int ch =0; ;
sun.misc.BASE64Encoder encoder= new sun.misc.BASE64Encoder();
byte[] contents = new byte[5000000];
int bytesRead = 0;
String strFileContents;
while ((bytesRead = bin.read(contents)) != -1) {
responseStrBuilder.append(encoder.encode(contents).getBytes());
}
myObj.addProperty("1",responseStrBuilder.toString());
out.println(myObj.toString());
Client side ajax code :
success: function(result)
{
if(result)
{
$('#dynamicCamping01').html('<img src='+result[Object.keys(result)[0]]+'/>');
$('#dynamicCampingDesc01').html("<h3>"+allData[0]+"</h3>");
}
else
{
alert("Something went wrong while retriving events");
}
getting data at client side but image is not displaying.
This one worked :
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0; ;
sun.misc.BASE64Encoder encoder= new sun.misc.BASE64Encoder();
byte[] contents = new byte[5000000];
int bytesRead = 0;
String strFileContents;
while ((bytesRead = bin.read(contents)) != -1) {
bout.write(encoder.encode(contents).getBytes());
}
bout.close();
fin.close();
bin.close();
out.close();
and main important part is on client converting image into UTF-8 and Base64 decoding.
$(imageIDSData[i]).html('<img src="data:image/jpeg;charset=utf-8;base64,'+imageData[i]+'"/> ');
$(imageNameIDSData[i]).html("<h3>"+allData[i]+"</h3>");

JAVA not in gzip format error

I have an inputstream and I tried to process it but it gave me this error "not in gzip format" but the file is in gzip format "Content-Encoding: gzip"
protected String readResponse(InputStream is) throws IOException {
StringBuffer string;
int b;
byte[] buffer;
String eol, s = null;
GZIPInputStream gis;
int read;
int index;
eol = new String(new byte[] {(byte)0, (byte)0, (byte)-1, (byte)-1});
buffer = new byte[1];
string = new StringBuffer();
while ( (b = is.read()) > 0 ) {
buffer[0] = (byte)b;
s = new String(buffer);
string.append(s);
index = string.indexOf(eol);
if ( index > 0 && index == string.length() - 4 ) {
break;
}
}
System.out.println(string);
gis = new GZIPInputStream(is); << here I got the error
buffer = new byte[1024];
while ( (read = gis.read(buffer)) > 0 ) {
string.append(new String(buffer, 0, read));
}
return string.toString();
}
any thoughts?
thanks
Seeing this line:
eol = new String(new byte[] {(byte)0, (byte)0, (byte)-1, (byte)-1});
is enough to arrive to a conclusion: you are doomed from the start.
DO NOT USE STRING FOR BINARY DATA.
bytes and chars have no relationship to one another; what you are doing here is roughly equivalent to the following:
final CharsetDecoder decoder = Charset.defaultCharset()
.newDecoder().onMalformedInput(CodingErrorAction.REPLACE);
final ByteBuffer buf = ByteBuffer.wrap(new byte[]{...});
final CharBuffer cbuf = decoder.decode(buf);
final String eol = new String(cbuf.array());
Note the REPLACE action. Any unmappable byte sequence will trigger the decoder to output the Unicode replacement character, U+FFFD (looks familiar, right?).
Now try and put REPORT instead.
What is more, you use the default charset... Which differs from platform to platform.
Your code should really just read the input stream and return a byte array. use a ByteArrayOutputStream.
And if you want to write to a file directly, it's easy: use Files.copy().
Anyway, fixed that for you:
// Note: return code is byte[]
protected byte[] readResponse(final InputStream in)
throws IOException
{
try (
final InputStream gzin = new GzipInputSream(in);
final ByteArrayOutputStream out = new ByteArrayOutputStream();
) {
final byte[] buf = new byte[4096];
int bytesRead;
while ((bytesRead = gzin.read(buf)) != -1)
out.write(buf, 0, bytesRead);
return out.toByteArray();
}
}
The problem could be you're advancing the file pointer in the input stream before you pass it to GZIPInputStream. GZIPInputStream expects the first few bytes to be a standard header.
Try moving new GZIPInputStream(is); before your while loop
There is so many things wrong in your code..... But lets try anyway.
So you have ascii header and after that there shoulbe gzipped part? Gzip file always starts with id bytes. These have the fixed values 'ID1 = 31 (0x1f, \037), ID2 = 139 (0x8b, \213)'. Can you find those from your inputstream. There you should start the gzipstream.
I have tested this with a file composed from a few header lines, followed by an empty line, and an appended gzipped text file. The latter is written, unexpanded, to x.gz and unzipped and read from there, assuming that it is a text file. (If it is a binary file, a BufferedReader is pointless.)
try/with resources and catch should be added, but that's just a technicality.
InputStream is = ...;
StringBuilder lsb = new StringBuilder();
int c = -1;
while( (c = is.read()) != -1 ){
if( c == '\n' ){
String line = lsb.toString();
if( line.matches( "\\s*" ) ){
break;
}
System.out.println( line );
lsb.delete( 0, lsb.length() );
} else {
lsb.append( (char)c );
}
}
byte[] buffer = new byte[1024];
int nRead = 0;
OutputStream os = new FileOutputStream( "x.gz" );
while ( (nRead = is.read(buffer, 0, buffer.length )) > 0 ) {
os.write( buffer, 0, nRead );
}
os.close();
is.close();
InputStream gis = new GZIPInputStream( new FileInputStream( "x.gz" ) );
InputStreamReader isr = new InputStreamReader( gis );
BufferedReader br = new BufferedReader(isr);
String line;
while( (line = br.readLine()) != null ){
System.out.println("line: " + line );
}
br.close();

Using Google feed api java

I'm trying to fetch some data using Google feed api. But line = reader.readLine() is always null.
URL url = new URL("https://ajax.googleapis.com/ajax/services/feed/find?" +
"v=1.0&q=Official%20Google%20Blog");
URLConnection connection = url.openConnection();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
builder.append(line);
}
JSONObject json = new JSONObject(builder.toString());
Try this
URL url = new URL("https://ajax.googleapis.com/ajax/services/feed/find?" +
"v=1.0&q=Official%20Google%20Blog");
URLConnection connection = url.openConnection();
ByteArrayOutputStream content = new ByteArrayOutputStream();
InputStream is = connection.getInputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) >= 0)
{
content.write(buffer, 0, len);
}
byte[] finalContent = content.toByteArray();
String str = new String(finalContent, "UTF8");
System.out.print(str);
Or other way is you can read the content-length header and read that till you get that much data.

Categories