Yesterday I started to transfer some code from a working C#-Example to the equivalent Java-Application.
While I can read/write bytes successfully in C# and with that, control any of my devices like powering them on, change the color of the LED-Lamp etc, it's not working in Java.
Here's the working C# example:
try
{
Int32 port = 4000;
TcpClient client = new TcpClient(server, port);
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
data = new Byte[256];
Int32 bytes = stream.Read(data, 0, data.Length);
stream.Close();
client.Close();
return data;
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
return null;
And this is the corresponding Java-Code I have which is not writing the "data" array correctly. I needed to change from byte to int because the target device is expecting numbers from 0 to 255 and a byte in Java covers from -128 to 127.
try
{
int port = 4000;
Socket socket = new Socket(server, port);
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
// send length of data first
dos.writeInt(data.length);
// append all the integers to the message
for(int i = 0; i < data.length; i++){
dos.writeInt(data[i]);
}
// confirm send
dos.flush();
data = new int[256];
InputStream in = socket.getInputStream();
byte[] b = new byte[in.available()];
in.read(b, 0, b.length);
dos.close();
out.close();
socket.close();
return data;
}
catch (Exception e)
{
System.console().format("Exception: {0}", e);
}
return null;
I hope you can help me and show me my error.