I need to send a message (in JSON format) to a IoT device connected on my local network. The device is a smart bulb that I would like to toggle at every request. I know the IP address and the port of the device.
I am already able to control it using a Python script, like so:
request = """{"id":1,"method":"toggle","params":["smooth",300]}\r\n""".encode("utf8")
print(request) # Prints: b'{"id":1,"method":"toggle","params":["smooth",300]}\r\n'
_socket= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
_socket.settimeout(5)
_socket.connect(('123.456.7.89', 12345))
_socket.send(request)
But I need to run it using Java/Kotlin. I tried converting the code, and so far I got this (in Kotlin):
val request = """{"id":0,"method":"toggle","params":["smooth",300]}\r\n""".encodeUtf8().toByteArray()
println(String(request, Charsets.UTF_8)) // Prints: {"id":0,"method":"toggle","params":["smooth",300]}\r\n
val socket = Socket()
val socketAddress = InetSocketAddress("123.456.7.89", 12345)
socket.connect(socketAddress, 5_000)
socket.getOutputStream().write(request)
This script runs without any exception, but it also doesn't work, and I couldn't find a way to proceed from here.
CodePudding user response:
In Java you can do it as following:
public class Client {
public static final String LOCALHOST = "localhost"; // Example host
public static final int PORT = 1234; // Example port
public static void main(String[] args) throws IOException {
try (Socket socket = new Socket(LOCALHOST, PORT)) {
System.out.println("Connected to Server!");
BufferedWriter socketWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
socketWriter.write("{\"id\":1,\"method\":\"toggle\",\"params\":[\"smooth\",300]}\n");
socketWriter.close();
}
System.out.println("Disconnected from server");
}
}
In case you have a JDK 15 you can use the new text block feature to write the String:
/*socketWriter.write("""
{"id":1,"method":"toggle","params":["smooth",300]}
""");*/