如何使用 Java 发送 M-SEARCH 查询

How to Send M-SEARCH Query with Java

我的网络上有一个 Roku 设备,我希望能够以编程方式发现它。 official Roku documentation 表示:

There is a standard SSDP multicast address and port (239.255.255.250:1900) that is used for local network communication. The Roku responds to M-SEARCH queries on this ip address and port.

In order to query for the roku ip address, your program can send the following request using the http protocol to 239.255.255.250 port 1900:

他们提供了一个使用 netcat 的示例,他们说可以使用 wireshark 来查找结果。他们还说:

The External Control Protocol enables the Roku to be controlled via the network. The External Control Service is discoverable via SSDP (Simple Service Discovery Protocol). The service is a simple RESTful API that can be accessed by programs in virtually any programming environment.

我有一个 java 程序可以根据其 IP 地址控制我的 Roku,我想实现一个使用此 SSDP 在网络上发现它的功能。

如何使用 java 发送 M-SEARCH 查询?我完全不知道如何做到这一点。它像 get/post 请求吗?如果有人能指出正确的方向,我将不胜感激!

我找到了 java 解决方案:

/* multicast SSDP M-SEARCH example for 
 * finding the IP Address of a Roku
 * device. For more info go to: 
 * http://sdkdocs.roku.com/display/sdkdoc/External+Control+Guide 
 */

import java.io.*;
import java.net.*;

class msearchSSDPRequest {
    public static void main(String args[]) throws Exception {
        /* create byte arrays to hold our send and response data */
        byte[] sendData = new byte[1024];
        byte[] receiveData = new byte[1024];

        /* our M-SEARCH data as a byte array */
        String MSEARCH = "M-SEARCH * HTTP/1.1\nHost: 239.255.255.250:1900\nMan: \"ssdp:discover\"\nST: roku:ecp\n"; 
        sendData = MSEARCH.getBytes();

        /* create a packet from our data destined for 239.255.255.250:1900 */
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("239.255.255.250"), 1900);

        /* send packet to the socket we're creating */
        DatagramSocket clientSocket = new DatagramSocket();
        clientSocket.send(sendPacket);

        /* recieve response and store in our receivePacket */
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);

        /* get the response as a string */
        String response = new String(receivePacket.getData());

        /* print the response */
        System.out.println(response);

        /* close the socket */
        clientSocket.close();
    }
}