Tomas Randomas Tomas Randomas - 2 years ago 113
Java Question

How to display received bytes as text in java?

first of all , i am very new to programming , and a task im trying to accomplish is :

send bytes from my delphi program to java server(done!)

display received bytes as text in a java server

T H E Question : How to display received bytes in java?

Thank you very mutch if you could help, that would save me atleast one more sleepless night.

My working code example from delphi application:

procedure sendInt(val: integer);
Socket.SendByte(byte(val shr 24));
Socket.SendByte(byte(val shr 16));
Socket.SendByte(byte(val shr 8));

The java server code i was able to put together , probably a nonsence.

ServerSocket sc=new ServerSocket(9999);
Socket s=sc.accept();
DataInputStream dos=new DataInputStream(s.getInputStream());
String msg=dos.readUTF();

What this does : If i run the java server, and send the bytes - returns null.
If i send continuous bytes - server does nothing, and only after i finish sending it displays a whole bunch of nulls, not sure if that helps, just trying to give as mutch information as possible. Thank you !

Answer Source

Assuming you want to pass through and display an int32 as formatted in your stream (you're sending big-endian), then the conceptually easiest way is:

InputStream is = s.getInputStream();
int val = 0;
for(int i = 0; i<4; i++) {
    val <<= 8; // does nothing first time
    val |=;

This assembles the received bytes into an int32 and prints it as a formatted string with newline.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download