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

标签 java networking ssdp

我的网络上有一个 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 程序可以控制我的 Roku 给它的 IP 地址,我想实现一个使用这个 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();
    }
}

关于java - 如何使用 Java 发送 M-SEARCH 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28402554/

相关文章:

用于重置网络适配器的 C#

rest - 在Golang中使HTTP请求非法路径

android - 如何使用 Android 的本地网络服务发现找到所有可用的服务

c# - UPnP 组播 : missing answers from M-SEARCH (Discovery)

java - Selenium NoSuchElementException

java - 我的程序出现错误

java - 我们可以一起选择并更新到数据库吗?

Android:SSDP 卡在 MulticastSocket.receive() 上

python - 使用 tcpdump 跳过 IP header

java - 通过枚举实现的单例在模块化趋势中仍然值得(即 Java 9+ 模块化和 Jigsaw 项目)