我需要向本地網路上連接的 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)
這個腳本運行沒有任何例外,但它也不起作用,我找不到從這里繼續的方法。
uj5u.com熱心網友回復:
在 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]}
""");*/
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/456319.html
上一篇:使用套接字編程接收訊息時的問題
