`
kiddsunhaibo1
  • 浏览: 98434 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

SIp学习实例

    博客分类:
  • sip
阅读更多
网站上关于基于sip的java编程实例实在是太少了,这个严重影响了sip的传播和发展,所以我上传了这个小实验,让大家参考下。

在做实验前,我们需要一些东西:
我的环境:
XP
Eclipse

需要包:

这个需要在网上自己找,或者hi我,我也可以给你们哈。----百度账号:时光可见

好了,现在看程序了哈,主要是三个文件。

MessageProcessor.java :
public interface MessageProcessor
{
    public void processMessage(String sender, String message);
    public void processError(String errorMessage);
    public void processInfo(String infoMessage);
}

SipLayer.java :

import java.text.ParseException;
import java.util.*;
import javax.sip.*;
import javax.sip.address.*;
import javax.sip.header.*;
import javax.sip.message.*;

public class SipLayer implements SipListener {

private MessageProcessor messageProcessor;

private String username;

private SipStack sipStack;

private SipFactory sipFactory;

private AddressFactory addressFactory;

private HeaderFactory headerFactory;

private MessageFactory messageFactory;

private SipProvider sipProvider;

/** Here we initialize the SIP stack. */
public SipLayer(String username, String ip, int port)
throws PeerUnavailableException, TransportNotSupportedException,
InvalidArgumentException, ObjectInUseException,
TooManyListenersException {

setUsername(username);
sipFactory = SipFactory.getInstance();
sipFactory.setPathName("gov.nist");
Properties properties = new Properties();
properties.setProperty("javax.sip.STACK_NAME", "TextClient");
properties.setProperty("javax.sip.IP_ADDRESS", ip);

// DEBUGGING: Information will go to files
// textclient.log and textclientdebug.log
properties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32");
properties.setProperty("gov.nist.javax.sip.SERVER_LOG", "textclient.txt");
properties.setProperty("gov.nist.javax.sip.DEBUG_LOG", "textclientdebug.log");

sipStack = sipFactory.createSipStack(properties);
headerFactory = sipFactory.createHeaderFactory();
addressFactory = sipFactory.createAddressFactory();
messageFactory = sipFactory.createMessageFactory();

// ListeningPoint tcp = sipStack.createListeningPoint(port, "tcp");
ListeningPoint udp = sipStack.createListeningPoint(port, "udp");

// sipProvider = sipStack.createSipProvider(tcp);
// sipProvider.addSipListener(this);

// suppose UDP is used as transport, Bob Cheng, 03-11-10
sipProvider = sipStack.createSipProvider(udp);
sipProvider.addSipListener(this);
}

/**
* This method uses the SIP stack to send a message.
*/
public void sendMessage(String to, String message) throws ParseException,
InvalidArgumentException, SipException {

SipURI from = addressFactory.createSipURI(getUsername(), getHost() + ":" + getPort());
Address fromNameAddress = addressFactory.createAddress(from);
fromNameAddress.setDisplayName(getUsername());
FromHeader fromHeader = headerFactory.createFromHeader(fromNameAddress, "textclientv1.0");

String username = to.substring(to.indexOf(":") + 1, to.indexOf("@"));
String address = to.substring(to.indexOf("@") + 1);

SipURI toAddress = addressFactory.createSipURI(username, address);
Address toNameAddress = addressFactory.createAddress(toAddress);
toNameAddress.setDisplayName(username);
ToHeader toHeader = headerFactory.createToHeader(toNameAddress, null);

SipURI requestURI = addressFactory.createSipURI(username, address);
requestURI.setTransportParam("udp");

ArrayList<ViaHeader> viaHeaders = new ArrayList<ViaHeader>();
ViaHeader viaHeader = headerFactory.createViaHeader(getHost(), getPort(), "udp", "branch1");
viaHeaders.add(viaHeader);

CallIdHeader callIdHeader = sipProvider.getNewCallId();

CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(1, Request.MESSAGE);

MaxForwardsHeader maxForwards = headerFactory.createMaxForwardsHeader(70);

Request request = messageFactory.createRequest(requestURI,
Request.MESSAGE, callIdHeader, cSeqHeader, fromHeader,
toHeader, viaHeaders, maxForwards);

SipURI contactURI = addressFactory.createSipURI(getUsername(), getHost());
contactURI.setPort(getPort());
Address contactAddress = addressFactory.createAddress(contactURI);
contactAddress.setDisplayName(getUsername());
ContactHeader contactHeader = headerFactory.createContactHeader(contactAddress);
request.addHeader(contactHeader);

ContentTypeHeader contentTypeHeader = headerFactory.createContentTypeHeader("text", "plain");
request.setContent(message, contentTypeHeader);

sipProvider.sendRequest(request);
}

/** This method is called by the SIP stack when a response arrives. */
public void processResponse(ResponseEvent evt) {
Response response = evt.getResponse();
int status = response.getStatusCode();

if ((status >= 200) && (status < 300)) { // Success!
messageProcessor.processInfo("--Sent");
return;
}

messageProcessor.processError("Previous message not sent: " + status);
}

/**
* This method is called by the SIP stack when a new request arrives.
*/
public void processRequest(RequestEvent evt) {
Request req = evt.getRequest();

String method = req.getMethod();
if (!method.equals("MESSAGE")) { // bad request type.
messageProcessor.processError("Bad request type: " + method);
return;
}

FromHeader from = (FromHeader) req.getHeader("From");
messageProcessor.processMessage(from.getAddress().toString(),
new String(req.getRawContent()));
Response response = null;
try { // Reply with OK
response = messageFactory.createResponse(200, req);
ToHeader toHeader = (ToHeader) response.getHeader(ToHeader.NAME);
toHeader.setTag("888"); // This is mandatory as per the spec.
ServerTransaction st = sipProvider.getNewServerTransaction(req);
st.sendResponse(response);
} catch (Throwable e) {
e.printStackTrace();
messageProcessor.processError("Can't send OK reply.");
}
}

/**
* This method is called by the SIP stack when there's no answer to a
* message. Note that this is treated differently from an error message.
*/
public void processTimeout(TimeoutEvent evt) {
messageProcessor
.processError("Previous message not sent: " + "timeout");
}

/**
* This method is called by the SIP stack when there's an asynchronous
* message transmission error.
*/
public void processIOException(IOExceptionEvent evt) {
messageProcessor.processError("Previous message not sent: " + "I/O Exception");
}

/**
* This method is called by the SIP stack when a dialog (session) ends.
*/
public void processDialogTerminated(DialogTerminatedEvent evt) {
}

/**
* This method is called by the SIP stack when a transaction ends.
*/
public void processTransactionTerminated(TransactionTerminatedEvent evt) {
}

public String getHost() {
int port = sipProvider.getListeningPoint().getPort();
String host = sipStack.getIPAddress();
return host;
}

public int getPort() {
int port = sipProvider.getListeningPoint().getPort();
return port;
}

public String getUsername() {
return username;
}

public void setUsername(String newUsername) {
username = newUsername;
}

public MessageProcessor getMessageProcessor() {
return messageProcessor;
}

public void setMessageProcessor(MessageProcessor newMessageProcessor) {
messageProcessor = newMessageProcessor;
}

}

TextClient.java :

import java.awt.event.*;
import javax.swing.*;
import java.net.InetAddress;

public class TextClient extends JFrame implements MessageProcessor {
private SipLayer sipLayer;

private JTextField fromAddress;
private JLabel fromLbl;
private JLabel receivedLbl;
private JTextArea receivedMessages;
private JScrollPane receivedScrollPane;
private JButton sendBtn;
private JLabel sendLbl;
private JTextField sendMessages;
private JTextField toAddress;
private JLabel toLbl;

public static void main(String[] args) {
if (args.length != 2) {
printUsage();
System.exit(-1);
}

try {
String username = args[0];
int port = Integer.parseInt(args[1]);
String ip = InetAddress.getLocalHost().getHostAddress();

System.out.println("--username = "+username
+"\n--port = "+port
+"\n--ip = "+ip);

SipLayer sipLayer = new SipLayer(username, ip, port);
TextClient tc = new TextClient(sipLayer);
sipLayer.setMessageProcessor(tc);

// tc.show();
tc.setVisible(true);
} catch (Throwable e) {
System.out.println("Problem initializing the SIP stack.");
e.printStackTrace();
System.exit(-1);
}
}

private static void printUsage() {
System.out.println("Syntax:");
System.out.println("  java -jar textclient.jar <username> <port>");
System.out.println("where <username> is the nickname of this user");
System.out.println("and <port> is the port number to use. Usually 5060 if not used by another process.");
System.out.println("Example:");
System.out.println("  java -jar textclient.jar snoopy71 5061");
}

public TextClient(SipLayer sip) {
super();
sipLayer = sip;
initWindow();
String from = "sip:" + sip.getUsername() + "@" + sip.getHost() + ":" + sip.getPort();
this.fromAddress.setText(from);
}

private void initWindow() {
receivedLbl = new JLabel();
sendLbl = new JLabel();
sendMessages = new JTextField();
receivedScrollPane = new JScrollPane();
receivedMessages = new JTextArea();
fromLbl = new JLabel();
fromAddress = new JTextField();
toLbl = new JLabel();
toAddress = new JTextField();
sendBtn = new JButton();

getContentPane().setLayout(null);

setTitle("TextClient");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});

receivedLbl.setText("Received Messages:");
receivedLbl.setAlignmentY(0.0F);
receivedLbl.setPreferredSize(new java.awt.Dimension(25, 100));
getContentPane().add(receivedLbl);
receivedLbl.setBounds(5, 0, 136, 20);

sendLbl.setText("Send Message:");
getContentPane().add(sendLbl);
sendLbl.setBounds(5, 150, 90, 20);

getContentPane().add(sendMessages);
sendMessages.setBounds(5, 170, 270, 20);

receivedMessages.setAlignmentX(0.0F);
receivedMessages.setEditable(false); //设置为不可编辑
receivedMessages.setLineWrap(true); //设置可换行
receivedMessages.setWrapStyleWord(true);//设置换行方式为单词边界换行
receivedScrollPane.setViewportView(receivedMessages);
receivedScrollPane
.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

getContentPane().add(receivedScrollPane);
receivedScrollPane.setBounds(5, 20, 270, 130);

fromLbl.setText("From:");
getContentPane().add(fromLbl);
fromLbl.setBounds(5, 200, 35, 15);

getContentPane().add(fromAddress);
fromAddress.setBounds(40, 200, 235, 20);
fromAddress.setEditable(false);

toLbl.setText("To:");
getContentPane().add(toLbl);
toLbl.setBounds(5, 225, 35, 15);

getContentPane().add(toAddress);
toAddress.setBounds(40, 225, 235, 21);

sendBtn.setText("Send");
sendBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
sendBtnActionPerformed(evt);
}
});

getContentPane().add(sendBtn);
sendBtn.setBounds(200, 255, 75, 25);

java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit()
.getScreenSize();
setBounds((screenSize.width - 288) / 2, (screenSize.height - 310) / 2,
288, 320);
}

private void sendBtnActionPerformed(ActionEvent evt) {

try {
String to = this.toAddress.getText();
String message = this.sendMessages.getText();
sipLayer.sendMessage(to, message);
} catch (Throwable e) {
e.printStackTrace();
this.receivedMessages.append("ERROR sending message: "
+ e.getMessage() + "\n");
}

}

public void processMessage(String sender, String message) {
this.receivedMessages.append("From " + sender + ": " + message + "\n");
}

public void processError(String errorMessage) {
this.receivedMessages.append("ERROR: " + errorMessage + "\n");
}

public void processInfo(String infoMessage) {
this.receivedMessages.append(infoMessage + "\n");
}
}


上面是一个简单的发送接收程序哈。
运行截图:



注意这里的ip和port是由电脑上获取的,要是你的程序不能运行,那可能是你的电脑没有连接、或者是连接断开。可以自行在程序中设置ip和port。

对这个程序的说明:
注意:这是一个本机发送本机接收的例子。

对于整个程序的分析:
* 在运行程序的时候,将自动获取发送方的username--bob、port--8000、ip--192.168.88.1
* 定义一个SipLayer变量sipLayer,传入参数(username、portip),
再将其传递给TextClient类的构造函数---这样在TextClient类中就可以调用SipLayer中的函数
* 定义一个TextClient类TC,并将其传入sipLayer.setMessageProcessor(TC)--这一步很重要
* 因为TextClient类实现了MessageProcessor接口,当SipLayer类中调用MessageProcessor中的函数时,
参数自动传递到TextClient类中实现的MessageProcessor接口的函数
* 进行窗口的初始化
* 点击发送按钮的时候,将消失发送到SipLayer中进行处理:sipLayer.sendMessage(to, message);
* 对数据进行包装和处理---这一步就不细说了
* 最后由sip供应商发送数据sipProvider.sendRequest(request);
* 因为之前说过了,这是一个本机发送本机接收的例子
* 数据在SipLayer类中的processRequest(RequestEvent evt)函数接收到,并进行处理

运行结果:
* 在输入为:df:jo@192.168.88.1:8000时,程序运行正常
* 在输入为::@192.168.88.1:8000时,程序运行正常

* 在改变ip前三位的任意数时,例::@191.168.88.1:8000
报错ERROR sending message: IO Exception occured while Sending Request
* 在改变ip的最后一位时,不能接收数据,无报错

* 在改变端口号时,例::@192.168.88.1:8001,不能接收数据,无报错
* 在发送数据为空时,不能接收数据,无报错
* 在去掉第一个":"时,例:sipjo@192.168.88.1:8000
报错ERROR sending message: String index out of range: -14
* 在去掉"@"时,例:sip:jo192.168.88.1:8000
报错ERROR sending message: String index out of range: -5

* 在第一个":"后面加上空格,例:sip: jo@192.168.88.1:8000
报错ERROR sending message: sip: jo@192.168.88.1:8000: Missing host name
* 在sip后面加上空格,程序正常运行
* 在用户名后面加上空格,例:sip:jo @192.168.88.1:8000
报错ERROR sending message: IO Exception occured while Sending Request
* 在@后面加上空格,例:sip:jo@ 192.168.88.1:8000
报错ERROR sending message: sip:jo@ 192.168.88.1:8000: Missing host name
分享到:
评论

相关推荐

    送给sip学习者(sip实例).doc

    本文档提供了一个基于Java编程的SIP实例,以帮助SIP学习者更好地理解和应用SIP协议。在Java中实现SIP通常需要使用特定的库,如osip2或eXosip2,但文档中没有明确提及这两个库,而是提到了一个简单的SIP层(SipLayer...

    SIP.rar_sip_sip 实例_sip协议

    9. **实例分析**:压缩包内的"SIP.pdf"很可能包含各种SIP交互的实例,比如如何发起一个通话邀请、处理不同类型的响应、如何处理错误情况等。这些实例将帮助读者通过实际场景更好地理解SIP协议的工作原理。 通过阅读...

    SIP消息实例讲解ppt.zip

    通过学习这些PPT,你可以掌握SIP协议的基本概念、消息格式、会话管理和多方通信的关键点,这对于理解和实施基于SIP的通信系统是非常有益的。同时,深入理解SIP协议有助于你在实际工作中解决各种网络通信问题,提升你...

    sip基于java的实例、开发包、资料

    总的来说,这个资源包为Java开发者提供了一个全面的SIP学习平台,从基础概念到实践案例,再到深入研究,都有所覆盖。通过深入学习和实践,你可以掌握SIP通信的核心技术,并具备开发高质量SIP应用的能力。

    JAIN SIP实例代码及文档

    **JAIN SIP实例代码及文档**是一份涵盖了JAIN SIP协议栈相关知识的资源集合,主要包含协议栈的JAR文件、详细的协议栈文档以及基于message实现的实例代码。这份资源对于理解并应用SIP(Session Initiation Protocol)...

    miniSipServer + peers 实面的SIP实例(含源码)

    这个实例包括了miniSipServer的使用以及peers的配置,提供了源码分析的机会,有助于深入理解SIP的工作原理和实际应用。 首先,我们需要了解SIP的基本概念。SIP由IETF定义,主要由用户代理(UA)、代理服务器、...

    java sip实例源码、开发包

    Java SIP实例源码与开发包提供了深入理解和应用SIP(Session Initiation Protocol)协议的绝佳素材,适合于Java开发者和通信技术爱好者。SIP是一种应用层控制协议,主要用于创建、修改和终止多媒体通信会话,如语音...

    sip实例源码

    【标题】:“SIP实例源码” ...通过深入学习这个SIP实例源码,开发者不仅可以掌握SIP协议的基本原理,还能了解到如何在Java环境中实现和调试SIP应用,这对于开发VoIP系统或其他基于SIP的通信解决方案至关重要。

    C#基于SIP协议的一些实例

    标题 "C#基于SIP协议的一些实例" 描述了如何在C#编程环境中利用SIP(Session Initiation Protocol)协议实现通信功能。SIP是一种应用层控制协议,用于建立、修改和终止多媒体通信会话,如语音通话、视频会议等。这个...

    sip.rar_phpsip_sip 实例_sip 解析

    **SIP(Session Initiation Protocol)详解** SIP(会话初始协议)是一种应用层控制协议,用于...对于深入学习和掌握SIP,阅读《sip协议分析.pdf》这样的资料将是十分有益的,它将提供更详细的理论知识和实践案例。

    sipservlet_demo_chatroom

    总的来说,【sipservlet_demo_chatroom】项目提供了一个实践SIP协议和SIP Servlets的实例,对学习和开发实时通信应用非常有帮助。通过研究源代码,开发者可以掌握如何构建一个基本的SIP聊天室,并在此基础上扩展出更...

    基于SIP的网络电话实例

    【标题】基于SIP的网络电话实例 在通信领域,SIP(Session Initiation Protocol)是一种用于控制多媒体通信会话...尽管这个实例的界面设计有待改进,但其核心功能的实现对于学习和理解VoIP通信机制具有很高的价值。

    SIP学习帮手SIP中文资料汇编

    **SIP学习帮手SIP中文资料汇编** SIP(Session Initiation Protocol)是一种用于控制多媒体通信会话(如语音和视频通话)的应用层协议。这个“SIP学习帮手SIP中文资料汇编”提供了丰富的中文资源,旨在帮助初学者更...

    sip协议学习

    SIP(Session Initiation Protocol)协议是互联网电话和多媒体通信的核心标准之一,由...通过深入学习和实践,我们可以利用SIP创建高效、灵活的通信解决方案,服务于各种应用场景,包括企业通信、移动通信、物联网等。

    sip应用的一个具体例子, c++的

    同时,学习如何使用OSIP库创建和解析SIP消息,是掌握SIP应用的关键。 此外,为了实现一个完整的SIP应用,还需要考虑网络连接、错误处理、多线程以及可能的安全问题,例如认证和加密。例如,使用TLS(Transport ...

    基于sip协议的程序例子

    **SIP(Session Initiation Protocol)协议详解** SIP,全称为Session Initiation Protocol,是一种应用层控制协议,主要用于创建、修改和终止多媒体通信...同时,这个实例也为学习和研究SIP提供了一个很好的起点。

    sip.rar_SIP java_java textclient_sip_基于SIP_基于sip的java

    通过学习和实践这个实例,开发者可以深入了解SIP协议的工作原理,以及如何在Java环境中有效地实现SIP应用。这对于构建VoIP服务、企业通信系统或者多媒体会议应用是非常有价值的。同时,掌握SIP协议也有助于开发者...

    Sip注册 Java实现

    1. **初始化SIP Stack**:使用`javax.sip.SipFactory`创建SIP堆栈实例,然后设置参数,如监听端口、协议类型(UDP/TCP/TLS)等。 2. **创建SIP会话**:通过SIP堆栈创建`javax.sip.SipContext`对象,它代表了SIP会话...

    基于Java的实例开发源码-SIP协议包 jSIP.zip

    通过分析这些代码,开发者可以学习到如何使用jSIP库来实现SIP协议的各种功能,如注册、邀请、接收和发送消息等。 5. `README.sipchat`:此文件通常包含项目简介、使用指南、注意事项等内容,对于理解和使用jSIP实例...

Global site tag (gtag.js) - Google Analytics