我需要向本地网络上连接的 IoT 设备发送消息(JSON 格式)。该设备是一个智能灯泡,我想在每次请求时切换。我知道设备的 IP 地址和端口。
我已经能够使用 Python 脚本来控制它,如下所示:
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)
但我需要使用 Java/Kotlin 运行它。我尝试转换代码,到目前为止我得到了这个(在 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)
这个脚本运行没有任何异常,但它也不起作用,我找不到从这里继续的方法。
在 Java 中,您可以执行以下操作:
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");
}
}
如果您有 JDK 15+,您可以使用新的文本块功能来编写字符串:
/*socketWriter.write("""
{"id":1,"method":"toggle","params":["smooth",300]}
""");*/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句