送给sip学习者sip实例.docx
《送给sip学习者sip实例.docx》由会员分享,可在线阅读,更多相关《送给sip学习者sip实例.docx(16页珍藏版)》请在冰豆网上搜索。
![送给sip学习者sip实例.docx](https://file1.bdocx.com/fileroot1/2023-5/23/c154c736-f5f2-472b-a5ad-6db1abf3e6f5/c154c736-f5f2-472b-a5ad-6db1abf3e6f51.gif)
送给sip学习者sip实例
网站上关于基于sip的java编程实例实在是太少了,这个严重影响了sip的传播和发展,所以我上传了这个小实验,让大家参考下。
在做实验前,我们需要一些东西:
我的环境:
XP
Eclipse
需要包:
这个需要在网上自己找,或者hi我,我也可以给你们哈。
----XX账号:
时光可见
好了,现在看程序了哈,主要是三个文件。
MessageProcessor.java:
publicinterfaceMessageProcessor
{
publicvoidprocessMessage(Stringsender,Stringmessage);
publicvoidprocessError(StringerrorMessage);
publicvoidprocessInfo(StringinfoMessage);
}
SipLayer.java:
importjava.text.ParseException;
importjava.util.*;
importjavax.sip.*;
importjavax.sip.address.*;
importjavax.sip.header.*;
importjavax.sip.message.*;
publicclassSipLayerimplementsSipListener{
privateMessageProcessormessageProcessor;
privateStringusername;
privateSipStacksipStack;
privateSipFactorysipFactory;
privateAddressFactoryaddressFactory;
privateHeaderFactoryheaderFactory;
privateMessageFactorymessageFactory;
privateSipProvidersipProvider;
/**HereweinitializetheSIPstack.*/
publicSipLayer(Stringusername,Stringip,intport)
throwsPeerUnavailableException,TransportNotSupportedException,
InvalidArgumentException,ObjectInUseException,
TooManyListenersException{
setUsername(username);
sipFactory=SipFactory.getInstance();
sipFactory.setPathName("gov.nist");
Propertiesproperties=newProperties();
properties.setProperty("javax.sip.STACK_NAME","TextClient");
properties.setProperty("javax.sip.IP_ADDRESS",ip);
//DEBUGGING:
Informationwillgotofiles
//textclient.logandtextclientdebug.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();
//ListeningPointtcp=sipStack.createListeningPoint(port,"tcp");
ListeningPointudp=sipStack.createListeningPoint(port,"udp");
//sipProvider=sipStack.createSipProvider(tcp);
//sipProvider.addSipListener(this);
//supposeUDPisusedastransport,BobCheng,03-11-10
sipProvider=sipStack.createSipProvider(udp);
sipProvider.addSipListener(this);
}
/**
*ThismethodusestheSIPstacktosendamessage.
*/
publicvoidsendMessage(Stringto,Stringmessage)throwsParseException,
InvalidArgumentException,SipException{
SipURIfrom=addressFactory.createSipURI(getUsername(),getHost()+":
"+getPort());
AddressfromNameAddress=addressFactory.createAddress(from);
fromNameAddress.setDisplayName(getUsername());
FromHeaderfromHeader=headerFactory.createFromHeader(fromNameAddress,"textclientv1.0");
Stringusername=to.substring(to.indexOf(":
")+1,to.indexOf("@"));
Stringaddress=to.substring(to.indexOf("@")+1);
SipURItoAddress=addressFactory.createSipURI(username,address);
AddresstoNameAddress=addressFactory.createAddress(toAddress);
toNameAddress.setDisplayName(username);
ToHeadertoHeader=headerFactory.createToHeader(toNameAddress,null);
SipURIrequestURI=addressFactory.createSipURI(username,address);
requestURI.setTransportParam("udp");
ArrayListviaHeaders=newArrayList();
ViaHeaderviaHeader=headerFactory.createViaHeader(getHost(),getPort(),"udp","branch1");
viaHeaders.add(viaHeader);
CallIdHeadercallIdHeader=sipProvider.getNewCallId();
CSeqHeadercSeqHeader=headerFactory.createCSeqHeader(1,Request.MESSAGE);
MaxForwardsHeadermaxForwards=headerFactory.createMaxForwardsHeader(70);
Requestrequest=messageFactory.createRequest(requestURI,
Request.MESSAGE,callIdHeader,cSeqHeader,fromHeader,
toHeader,viaHeaders,maxForwards);
SipURIcontactURI=addressFactory.createSipURI(getUsername(),getHost());
contactURI.setPort(getPort());
AddresscontactAddress=addressFactory.createAddress(contactURI);
contactAddress.setDisplayName(getUsername());
ContactHeadercontactHeader=headerFactory.createContactHeader(contactAddress);
request.addHeader(contactHeader);
ContentTypeHeadercontentTypeHeader=headerFactory.createContentTypeHeader("text","plain");
request.setContent(message,contentTypeHeader);
sipProvider.sendRequest(request);
}
/**ThismethodiscalledbytheSIPstackwhenaresponsearrives.*/
publicvoidprocessResponse(ResponseEventevt){
Responseresponse=evt.getResponse();
intstatus=response.getStatusCode();
if((status>=200)&&(status<300)){//Success!
messageProcessor.processInfo("--Sent");
return;
}
messageProcessor.processError("Previousmessagenotsent:
"+status);
}
/**
*ThismethodiscalledbytheSIPstackwhenanewrequestarrives.
*/
publicvoidprocessRequest(RequestEventevt){
Requestreq=evt.getRequest();
Stringmethod=req.getMethod();
if(!
method.equals("MESSAGE")){//badrequesttype.
messageProcessor.processError("Badrequesttype:
"+method);
return;
}
FromHeaderfrom=(FromHeader)req.getHeader("From");
messageProcessor.processMessage(from.getAddress().toString(),
newString(req.getRawContent()));
Responseresponse=null;
try{//ReplywithOK
response=messageFactory.createResponse(200,req);
ToHeadertoHeader=(ToHeader)response.getHeader(ToHeader.NAME);
toHeader.setTag("888");//Thisismandatoryasperthespec.
ServerTransactionst=sipProvider.getNewServerTransaction(req);
st.sendResponse(response);
}catch(Throwablee){
e.printStackTrace();
messageProcessor.processError("Can'tsendOKreply.");
}
}
/**
*ThismethodiscalledbytheSIPstackwhenthere'snoanswertoa
*message.Notethatthisistreateddifferentlyfromanerrormessage.
*/
publicvoidprocessTimeout(TimeoutEventevt){
messageProcessor
.processError("Previousmessagenotsent:
"+"timeout");
}
/**
*ThismethodiscalledbytheSIPstackwhenthere'sanasynchronous
*messagetransmissionerror.
*/
publicvoidprocessIOException(IOExceptionEventevt){
messageProcessor.processError("Previousmessagenotsent:
"+"I/OException");
}
/**
*ThismethodiscalledbytheSIPstackwhenadialog(session)ends.
*/
publicvoidprocessDialogTerminated(DialogTerminatedEventevt){
}
/**
*ThismethodiscalledbytheSIPstackwhenatransactionends.
*/
publicvoidprocessTransactionTerminated(TransactionTerminatedEventevt){
}
publicStringgetHost(){
intport=sipProvider.getListeningPoint().getPort();
Stringhost=sipStack.getIPAddress();
returnhost;
}
publicintgetPort(){
intport=sipProvider.getListeningPoint().getPort();
returnport;
}
publicStringgetUsername(){
returnusername;
}
publicvoidsetUsername(StringnewUsername){
username=newUsername;
}
publicMessageProcessorgetMessageProcessor(){
returnmessageProcessor;
}
publicvoidsetMessageProcessor(MessageProcessornewMessageProcessor){
messageProcessor=newMessageProcessor;
}
}
TextClient.java:
importjava.awt.event.*;
importjavax.swing.*;
import.InetAddress;
publicclassTextClientextendsJFrameimplementsMessageProcessor{
privateSipLayersipLayer;
privateJTextFieldfromAddress;
privateJLabelfromLbl;
privateJLabelreceivedLbl;
privateJTextAreareceivedMessages;
privateJScrollPanereceivedScrollPane;
privateJButtonsendBtn;
privateJLabelsendLbl;
privateJTextFieldsendMessages;
privateJTextFieldtoAddress;
privateJLabeltoLbl;
publicstaticvoidmain(String[]args){
if(args.length!
=2){
printUsage();
System.exit(-1);
}
try{
Stringusername=args[0];
intport=Integer.parseInt(args[1]);
Stringip=InetAddress.getLocalHost().getHostAddress();
System.out.println("--username="+username
+"\n--port="+port
+"\n--ip="+ip);
SipLayersipLayer=newSipLayer(username,ip,port);
TextClienttc=newTextClient(sipLayer);
sipLayer.setMessageProcessor(tc);
//tc.show();
tc.setVisible(true);
}catch(Throwablee){
System.out.println("ProbleminitializingtheSIPstack.");
e.printStackTrace();
System.exit(-1);
}
}
privatestaticvoidprintUsage(){
System.out.println("Syntax:
");
System.out.println("java-jartextclient.jar");
System.out.println("whereisthenicknameofthisuser");
System.out.println("andistheportnumbertouse.Usually5060ifnotusedbyanotherprocess.");
System.out.println("Example:
");
System.out.println("java-jartextclient.jarsnoopy715061");
}
publicTextClient(SipLayersip){
super();
sipLayer=sip;
initWindow();
Stringfrom="sip:
"+sip.getUsername()+"@"+sip.getHost()+":
"+sip.getPort();
this.fromAddress.setText(from);
}
privatevoidinitWindow(){
receivedLbl=newJLabel();
sendLbl=newJLabel();
sendMessages=newJTextField();
receivedScrollPane=newJScrollPane();
receivedMessages=newJTextArea();
fromLbl=newJLabel();
fromAddress=newJTextField();
toLbl=newJLabel();
toAddress=newJTextField();
sendBtn=newJButton();
getContentPane().setLayout(null);
setTitle("TextClient");
addWindowListener(newWindowAdapter(){
publicvoidwindowClosing(WindowEventevt){
System.exit(0);
}
});
receivedLbl.setText("ReceivedMessages:
");
receivedLbl.setAlignmentY(0.0F);
receivedLbl.setPreferredSize(newjava.awt.Dimension(25,100));
getContentPane().add(receivedLbl);
receivedLbl.setBounds(5,0,136,20);
sendLbl.setText("SendMessage:
");
getContentPane().add(sendLbl);
sendLb