本文仅用于作者学习,疏漏之处在所难免,出了虾米问题拒不负责。欢迎各位牛X踊跃拍砖赐教。
本文的理想读者是熟悉SIP协议但对SIP Servlet还不太了解。能够清楚SIP各个关键要素以及彼此间的逻辑联系和协议实现。如果你只是初学者建议把RFC反复看几遍,感觉就有了,不要老想取巧偷懒,以为看看博客上的介绍就对SIP了如指掌。我当年也是这样跌打滚爬过来的,坑爹的绕了不少弯路,最后还是老老实实看RFC,受益匪浅。废话少说,下面进入正题。
1. SIP Servlet概念
JSR 289中自己给SIP Servlet下了定义:
A SIP servlet is a Java-based application component which is managed by a SIP servlet container and which performs SIP signaling. Like other Java-based components, servlets are platform independent Java classes that are compiled to platform neutral bytecode that can be loaded dynamically into and run by a Java-enabled SIP application server. Containers, sometimes called servlet engines, are server extensions that provide servlet functionality. Servlets interact with (SIP) clients by exchanging request and response messages through the servlet container.
如果你之前已经使用过Http Servlet,你会对这个定义感到很亲切。简单的理解,SIP Servlet作为一个中间件,能够将你的项目组从一大堆SIP底层协议实现必须的代码中解救出来(前提是你会使用它且能够用的好),使你能够专注于上层业务逻辑的实现。
但这并不意味着SIP Servlet能够让你在完全不懂SIP协议的前提下,自动屏蔽掉所有与SIP有关的实现细节,然后像你期望的那样跑起来。在我看来,它只能减少你搭建SIP协议环境的工作量,但你至少要清楚,它在底层替你做了些什么,又有什么没有为你做(或者说它无法做到),需要你来自行实现。SIP Servlet从设计到实现都为开发者留足了空间(或者说难听点,是给你留了很多协议的后门让你取巧),我在后边的讲解或许会提到一些,所以你必须有足够的实力来驾驭它,而不是被它驾驭。
在这里,需要稍微提及jain sip的概念。Jain sip是一个java的sip协议栈,它几乎为所有java sip的上层开发提供底层支撑。比较通俗的说,Jain sip提供了实现SIP协议最基本的原材料,比如SIP Requests和Response的基本模型、客户端事务和服务器端事务的基本模型等等(具体你可以去看jain sip的文档)。你可以很方便的使用jain sip获取SIP报文中的信息并处理它,但具体的SIP业务逻辑,jain并没有帮你实现,你需要按照自己的RFC 的理解来实现你所需要的SIP功能。所以直接使用协议栈来开发SIP是很辛苦的说。
2. SIP Servlet入门
一、 基本概念
再次强调,此处需要你已经清晰理解SIP协议中的事务(transaction,唯一标识方法)、会话(Dialog,唯一标识方法)、UAC、UAS、Proxy(SipServlet在1.1版已经明确宣布不再支持无状态代理)、B2BUA、Request(INVITE、REGISTER、BYE、CANCEL、ACK、OPTIONS等)、Response(100-699状态码)等概念。
在我看来,可以分两个视角来将Sip Servlet提供的资源和模型分为两类。
一类是以开发者的视角:
Container(容器,Servlet基本概念,由Jboss、Tomcat等提供)->操纵->
->Applications(应用程序)->操纵->
->Servlets(每个应用程序内含多个Servlets) ->操纵->
->每个Servlet中描述业务逻辑
一类是以用户的角度:
用户操作软件(比如发起一个call)->创建->
->Application 实例 ->创建->
->Application Session ->创建->
->SipSessions(共享Application Session资源,一个SipSession约等于一个Dialog) ->创建和处理->
->Requests and Responses
而这两类在资源处理上又有交叠的部分,但总的来说一个应用程序(Application)根据实际运行情况产生多个Application Instances(应用程序实例)。同时,一个应用程序也包含多个Servlets,每个Servlets都能够操作到这些Application Instances。
下面,我们从开发者的角度讲解,应该如何设计一个SipServlet程序。
上面描述中涉及的关键概念将在下一篇中详细介绍。
先贴一个简单的例子代码,了解一下Servlet的基本结构。是根据mobicents sip servlet的ClickToCall改写的,添加了部分注释,应该理解起来问题不大。
- package org.mobicents.servlet.sip.example;
- import java.io.IOException;
- import java.util.HashMap;
- import java.util.Properties;
- import javax.naming.Context;
- import javax.naming.InitialContext;
- import javax.naming.NamingException;
- import javax.servlet.Servlet;
- import javax.servlet.ServletConfig;
- import javax.servlet.ServletException;
- import javax.servlet.sip.Address;
- import javax.servlet.sip.SipErrorEvent;
- import javax.servlet.sip.SipErrorListener;
- import javax.servlet.sip.SipFactory;
- import javax.servlet.sip.SipServlet;
- import javax.servlet.sip.SipServletRequest;
- import javax.servlet.sip.SipServletResponse;
- import javax.servlet.sip.SipSession;
- import javax.servlet.sip.annotation.SipListener;
- import org.apache.log4j.Logger;
- @javax.servlet.sip.annotation.SipServlet(loadOnStartup = 1, applicationName = "ClickToCallAsyncApplication")
- @SipListener
- // From和To的所有交互,都通过此应用程序交互
- // 它截取报文,改写头部后转发
- public class SimpleSipServlet extends SipServlet implements SipErrorListener,
- Servlet {
- private static final long serialVersionUID = 1L;
- private static Logger logger = Logger.getLogger(SimpleSipServlet.class);
- private static final String CONTACT_HEADER = "Contact";
- private SipFactory sipFactory;
- public SimpleSipServlet() {
- }
- @Override
- public void init(ServletConfig servletConfig) throws ServletException {
- super.init(servletConfig);
- logger.info("the simple sip servlet has been started");
- try {
- // Getting the Sip factory from the JNDI Context
- Properties jndiProps = new Properties();
- Context initCtx = new InitialContext(jndiProps);
- Context envCtx = (Context) initCtx.lookup("java:comp/env");
- sipFactory = (SipFactory) envCtx.lookup("sip/org.mobicents.servlet.sip.example.SimpleApplication/SipFactory");
- logger.info("Sip Factory ref from JNDI : " + sipFactory);
- //将测试机的注册信息添加进入
- HashMap<String, String> users = (HashMap<String, String>) getServletContext().getAttribute("registeredUsersMap");
- if (users == null) {
- users = new HashMap<String, String>();
- }
- String fromURI = "sip:[email protected]:8889";
- String ContactURI = "sip:[email protected]:8889";
- users.put(fromURI, ContactURI);
- fromURI = "sip:[email protected]:8888";
- ContactURI = "sip:[email protected]:8888";
- users.put(fromURI, ContactURI);
- fromURI = "sip:[email protected]:7777";
- ContactURI = "sip:[email protected]:7777";
- users.put(fromURI, ContactURI);
- fromURI = "sip:[email protected]:6666";
- ContactURI = "sip:[email protected]:6666";
- users.put(fromURI, ContactURI);
- getServletContext().setAttribute("registeredUsersMap", users);
- } catch (NamingException e) {
- throw new ServletException("Uh oh -- JNDI problem !", e);
- }
- }
- @Override
- protected void doInvite(SipServletRequest req) throws ServletException,
- IOException {
- logger.info("Click2Dial don't handle INVITE by CYX. Here's the one we got : " + req.toString());
- }
- @Override
- protected void doOptions(SipServletRequest req) throws ServletException,
- IOException {
- logger.info("Got : " + req.toString());
- req.createResponse(SipServletResponse.SC_OK).send();
- }
- @Override
- // 当服务器收到从To Addr处发回的 2XX响应
- // 但此时From Addr实际上并没有发出过INVITE,是由Web Servlet处代为发送的
- // To的Dialog先发送,From的Dialog后发送
- // Session中的inviteSent attrabute设置
- // ToDialog收到对应2XX后会调用doSuccessResponse(),顺利处理完成后会将inviteSent set True
- // FromDialog收到对应2XX后,设置好content SDP后,将两个ACK同时发现两端
- protected void doSuccessResponse(SipServletResponse resp)
- throws ServletException, IOException {
- logger.info("Got OK by CYX\n");
- SipSession session = resp.getSession();
- if (resp.getStatus() == SipServletResponse.SC_OK) {
- Boolean inviteSent = (Boolean) session.getAttribute("InviteSent");
- // 说明后续要发送给From的INVITE已经被发送
- if (inviteSent != null && inviteSent.booleanValue()) {
- return;
- }
- // 获取在WebServlet处填入的FromAddr
- Address secondPartyAddress = (Address) resp.getSession().getAttribute("SecondPartyAddress");
- // FromDialog没有设置secondPartyAddress
- // 说明收到的是ToDialog发送的2XX
- if (secondPartyAddress != null) {
- // getRemoteParty()获取ToAddr
- // 由SipServlet向FromAddr处发起邀请
- // 但实际并没有INVITE从to地址对应处发出,而是从服务器对应出口ip处发向from地址
- // 此方法同时创建一个新的SipSession通过sipFactory
- // The returned request object exists in a new SipSession which
- // belongs to the specified SipApplicationSession.
- SipServletRequest invite = sipFactory.createRequest(resp.getApplicationSession(), "INVITE", session.getRemoteParty(), secondPartyAddress);
- logger.info("Found second party -- sending INVITE to "
- + secondPartyAddress);
- // 如果contentType为SDP
- // 将response(ToAddr)中得到的content发送给FromAddr
- // 因为SDP协商可以发生在(1)INVITE-response
- // 也可以发生在(2)response-ACK
- // Dialog(From)由于INVITE(WebServlet发送)中没有写入SDP,故采用方式(2)
- // Dialog(To)由于收到了From的response,所以采用方式(1)
- String contentType = resp.getContentType();
- if (contentType.trim().equals("application/sdp")) {
- invite.setContent(resp.getContent(), "application/sdp");
- }
- // 将From的Dialog与To的Dialog关联起来
- session.setAttribute("LinkedSession", invite.getSession());
- invite.getSession().setAttribute("LinkedSession", session);
- // 为To的Dialog创建ACK响应
- // 并将ACK响应保存在From的Dialog中
- SipServletRequest ack = resp.createAck();
- invite.getSession().setAttribute("FirstPartyAck", ack);
- invite.getSession().setAttribute("FirstPartyContent", resp.getContent());
- Call call = (Call) session.getAttribute("call");
- // The call links the two sessions, add the new session to the call
- // call关联了这两个Dialog
- call.addSession(invite.getSession());
- // 为From 的Dialog关联call
- invite.getSession().setAttribute("call", call);
- invite.send();
- //FromDialog的"InviteSent"属性被置为true
- session.setAttribute("InviteSent", Boolean.TRUE);
- } // 说明收到的是FromDialog收到的2XX
- else {
- String cSeqValue = resp.getHeader("CSeq");
- // Returns the index within this string of the first occurrence of the specified substring.
- // 即indexOf返回"INVITE"的索引,-1为没有查找到(说明方法不匹配)
- if (cSeqValue.indexOf("INVITE") != -1) {
- logger.info("Got OK from second party -- sending ACK");
- SipServletRequest secondPartyAck = resp.createAck();
- SipServletRequest firstPartyAck = (SipServletRequest) resp.getSession().getAttribute("FirstPartyAck");
- // if (resp.getContentType() != null && resp.getContentType().equals("application/sdp")) {
- firstPartyAck.setContent(resp.getContent(),
- "application/sdp");
- secondPartyAck.setContent(resp.getSession().getAttribute("FirstPartyContent"),
- "application/sdp");
- // }
- firstPartyAck.send();
- secondPartyAck.send();
- }
- }
- }
- }
- @Override
- protected void doErrorResponse(SipServletResponse resp) throws ServletException,
- IOException {
- // If someone rejects it remove the call from the table
- CallStatusContainer calls = (CallStatusContainer) getServletContext().getAttribute("activeCalls");
- calls.removeCall(resp.getFrom().getURI().toString(), resp.getTo().getURI().toString());
- calls.removeCall(resp.getTo().getURI().toString(), resp.getFrom().getURI().toString());
- }
- @Override
- protected void doBye(SipServletRequest request) throws ServletException,
- IOException {
- logger.info("Got bye");
- SipSession session = request.getSession();
- SipSession linkedSession = (SipSession) session.getAttribute("LinkedSession");
- if (linkedSession != null) {
- SipServletRequest bye = linkedSession.createRequest("BYE");
- logger.info("Sending bye to " + linkedSession.getRemoteParty());
- bye.send();
- }
- CallStatusContainer calls = (CallStatusContainer) getServletContext().getAttribute("activeCalls");
- calls.removeCall(request.getFrom().getURI().toString(), request.getTo().getURI().toString());
- calls.removeCall(request.getTo().getURI().toString(), request.getFrom().getURI().toString());
- SipServletResponse ok = request.createResponse(SipServletResponse.SC_OK);
- ok.send();
- //notifyStatus("Received Bye request");
- }
- /**
- * {@inheritDoc}
- */
- @Override
- protected void doResponse(SipServletResponse response)
- throws ServletException, IOException {
- logger.info("SimpleProxyServlet: Got response:\n" + response);
- super.doResponse(response);
- }
- /**
- * {@inheritDoc}
- */
- public void noAckReceived(SipErrorEvent ee) {
- logger.info("SimpleProxyServlet: Error: noAckReceived.");
- }
- /**
- * {@inheritDoc}
- */
- public void noPrackReceived(SipErrorEvent ee) {
- logger.info("SimpleProxyServlet: Error: noPrackReceived.");
- }
- protected void doRegister(SipServletRequest req) throws ServletException, IOException {
- logger.info("Received register request by CYX: " + req.getTo());
- int response = SipServletResponse.SC_OK;
- SipServletResponse resp = req.createResponse(response);
- HashMap<String, String> users = (HashMap<String, String>) getServletContext().getAttribute("registeredUsersMap");
- if (users == null) {
- users = new HashMap<String, String>();
- }
- getServletContext().setAttribute("registeredUsersMap", users);
- Address address = req.getAddressHeader(CONTACT_HEADER);
- String fromURI = req.getFrom().getURI().toString();
- int expires = address.getExpires();
- if (expires < 0) {
- expires = req.getExpires();
- }
- if (expires == 0) {
- users.remove(fromURI);
- logger.info("User " + fromURI + " unregistered by CYX\n");
- } else {
- resp.setAddressHeader(CONTACT_HEADER, address);
- users.put(fromURI, address.getURI().toString());
- logger.info("User " + fromURI
- + " registered with an Expire time of " + expires + "by CYX\n");
- }
- //notifyStatus("Received register event");
- resp.send();
- }
- // /*
- // * Any SIP Servlets method that wish to trigger an update to the client's page will use this method.
- // * For example doRegister use it to update the page every time a new user registers.
- // */
- // protected void notifyStatus(String event) {
- // BlockingQueue<String> eventsQueue = (LinkedBlockingQueue<String>) getServletContext().getAttribute("eventsQueue");
- //// if (eventsQueue == null) eventsQueue = new LinkedBlockingQueue<String>();
- //// getServletContext().setAttribute("eventsQueue", eventsQueue);
- //
- // try {
- // eventsQueue.put(event);
- // } catch (InterruptedException e) {
- // e.printStackTrace();
- // }
- // }
- }
本文出自 “9ccc9” 博客,转载请与作者联系!