I'm trying to communicate Modrssim (Modbus Simulator) with a java class. I'm sending a query to modsim and it responds to that. But when I try to read the response I can't get the proper character.
Here is my code:
import java.net.*;
import java.io.*;
class client
{
public static void main(String args[]) throws IOException
{
Socket s=null;
BufferedReader b=null;
char data[] ={0,0,0,0,0,6,1,2,0,2,0,0};
try
{
s=new Socket("199.199.51.7",502);
OutputStreamWriter writer = new OutputStreamWriter(s.getOutputStream());
BufferedWriter bw = new BufferedWriter(writer);
System.out.println("Sending Data....");
bw.write(data);
bw.flush();
b=new BufferedReader(new InputStreamReader(s.getInputStream()));
}
catch(UnknownHostException u)
{
System.err.println("I don't know host");
System.exit(0);
}
String inp;
System.out.println("Receiving......");
while((inp=b.readLine())!=null)
{
System.out.println(inp);
System.out.println("dONE");
}
b.close();
s.close();
}
}
As a response I'm getting 00 00 00 00 00 03 01 02 00 in modsim. An image of the response in MOdsim is here:
But while reading it, it shows a heart and two smilies. Data received:
You problem is simple: you can't just receive any kind of bytes and assume that sending them to System.out.println() will just do the right thing.
A byte is not a character or a String. It is just a binary value; and those can't be printed that "easily".
One thing you could try: print your bytes as HEX values, see here for some ideas around that.