如何使用Java/Kotlin插座将消息发送到本地网络的设备?

发布于 2025-01-18 13:33:43 字数 1040 浏览 0 评论 0原文

我需要将消息(以JSON格式)发送到我本地网络上连接的IoT设备。该设备是一个智能灯泡,我想按每个请求切换。我知道设备的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)

此脚本在没有任何例外的情况下运行,但也没有用,我找不到从这里开始的方法。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吃颗糖壮壮胆 2025-01-25 13:33:43

在 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]}
    """);*/

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]}
    """);*/
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文