正在解析 Java 中的 SDP 消息字符串

Parsing SDP message string in Java

目前我正在开发使用 SDP 消息建立连接的应用程序。我需要做的是为 SDP 消息的字符串表示创建解析器并创建某种表示信息的结构,同时从现有结构创建此类消息。

来自 RFC 4566 的示例:

  v=0
  o=jdoe 2890844526 2890842807 IN IP4 10.47.16.5
  s=SDP Seminar
  i=A Seminar on the session description protocol
  u=http://www.example.com/seminars/sdp.pdf
  e=j.doe@example.com (Jane Doe)
  c=IN IP4 224.2.17.12/127
  t=2873397496 2873404696
  a=recvonly
  m=audio 49170 RTP/AVP 0
  m=video 51372 RTP/AVP 99
  a=rtpmap:99 h263-1998/90000

我的问题是:是否有内置的 Java 工具来解析此类消息? 我在 github 上看到了一些这样做的示例,但由于我是该主题的新手,因此我无法确定哪种解决方案最适合此类任务。

是的,Java 有一些名为 Jain SIP 的内置 SIP 功能。它在媒体部分非常薄弱(没有良好的编解码器支持),但是对于信令处理它应该满足您的需求。

示例:

import javax.sdp.*;
import javax.sip.*;

ContentTypeHeader contentType = (ContentTypeHeader) msg.getHeader(ContentTypeHeader.NAME);
ContentLengthHeader contentLen = (ContentLengthHeader) msg.getHeader(ContentLengthHeader.NAME);

if ( contentLen.getContentLength() > 0 && contentType.getContentSubType().equals("sdp") ){
    String charset = null;

    if (contentType != null)
        charset = contentType.getParameter("charset");
    if (charset == null)
        charset = "UTF-8"; // RFC 3261

    //Save the SDP content in a String
    byte[] rawContent = msg.getRawContent();
    String sdpContent = new String(rawContent, charset);

    //Use the static method of SdpFactory to parse the content
    SdpFactory sdpFactory = SdpFactory.getInstance();
    SessionDescription sessionDescription = sdpFactory.createSessionDescription(sdpContent);
    Origin origin = sessionDescription.getOrigin();

    System.out.println("A Session ID is " + origin.getSessionId());
} else {
    System.out.println("It is not a SDP content");
}

如果您不喜欢这样,那么只需使用开源 SDP 解析器,例如 jain sip or jsdp

您也可以按照 RFC 4566 自己动手完成,因为 SDP 解析非常简单,只需进行一些字符串操作即可完成。