⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mymessenger.java

📁 * This a simple tool to send/receive UDP packet based on a * free software developed by Neil Deas
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
		while (m_Listening)
		{
			DatagramPacket packet = new DatagramPacket(new byte[packetSize], packetSize);
			try
			{
				m_DatagramSocket.receive(packet);
				if ( null != m_Observer )
				{
					printDebug("");
					printDebug("Length of packet received " + packet.getLength());
          m_Observer.notify(packet);
				}
				packet.setLength(packetSize);
			}
			catch(IOException e)
			{
				System.out.println("Error receiving datagram packet " + e);
			}


			try
			{
       Thread.sleep(250);
			}
			catch(InterruptedException e)
			{
			}
		}
	}

  /**
  * Modified implementation of MessengerObserver interface.
  * The DatagramPacket is passed as parameter instead of a String
  * so that more information is preserved.
  */
	public void notify(DatagramPacket datapacket)
	{
		String response = new String(datapacket.getData(), 0, datapacket.getLength());
		MyMsg msg = new MyMsg(response);

		// If the incoming msg is a heartbeat, generate response automatically
		// else, extract the CallID/CSeq for later use.
    boolean b_isOptions = msg.isOptions();
    
    if(b_isOptions)
    {
    	buildOptionsResp(msg);
      printDebug("~OPTIONS~");
    }
		// Screen the options to make the output more clear.
    else
		{
	    this.myOutput("");
			this.myOutput(" *** Start of Response *** ");
	    Calendar Cc=Calendar.getInstance();
  	  String MyTimestamp=Cc.get(Calendar.YEAR)+"-"+(Cc.get(Calendar.MONTH)+1)+"-"+Cc.get(Calendar.DAY_OF_MONTH)+" "+Cc.get(Calendar.HOUR_OF_DAY)+":"+Cc.get(Calendar.MINUTE)+":"+Cc.get(Calendar.SECOND);
			this.myOutput(" Packet received at: "+ MyTimestamp);
			try
			{
				this.myOutput(" From : " + datapacket.getAddress()+ " To : " + InetAddress.getLocalHost().toString());
			}
			catch (UnknownHostException e)
			{
				System.err.println(e);
			}

			this.myOutput(response);
			this.myOutput(" *** End of Response *** ");
  	  this.myOutput("");

      // Some automation here to faciliate the testing.
      if(msg.isRegister())
      {
        MyMsg o1Msg = MyMsgBuilder.buildRegisterResp100(msg);
        if(o1Msg!=null)
        {
          // Hard Coded to Local IP... 
          // Assumption is that both the SIP Client and SIP Tester are on the same machine.
          this.send(LclIP, Integer.parseInt(RmtPort), o1Msg.toString().getBytes());
        }
        MyMsg o2Msg = MyMsgBuilder.buildRegisterResp200(msg);
        if(o2Msg!=null)
        {
          // Hard Coded to Local IP... 
          // Assumption is that both the SIP Client and SIP Tester are on the same machine.
          this.send(LclIP, Integer.parseInt(RmtPort), o2Msg.toString().getBytes());
        }
        printDebug("~REGISTRATION COMPLETED");
      }

      if(msg.isInvite())
      {
        if(updateInvite(msg))
        {
          this.printDebug("New Transaction Detected !! ");
          this.printDebug("Default INVITE Msg Updated!!");
        }
        if(AutoAckInv)
        {
          MyMsg oMsg=MyMsgBuilder.build100(msg);
          if(oMsg!=null)
          {
				    this.send(SIPIP, Integer.parseInt(RmtPort), oMsg.toString().getBytes());
          }
          printDebug("~INVITE Auto Ack'ed~");
        }
      }
      
      if(msg.isBye() && this.AutoAckBye)
      {
        MyMsg oMsg=MyMsgBuilder.build200Bye(msg);
        if(oMsg!=null)
        {
		  		  this.send(SIPIP, Integer.parseInt(RmtPort), oMsg.toString().getBytes());
        }
        printDebug("~Bye~");
      }
      
      LastRevMsg=msg;
 			System.out.print("Your Command Please>");
 		}
	}

  private void buildOptionsResp(MyMsg msg)
  {
    MyMsg o1Msg = MyMsgBuilder.buildOptionsResp100(msg);
		this.send(VRDNIP, Integer.parseInt(RmtPort), o1Msg.toString().getBytes(),false);
		
		MyMsg o2Msg = MyMsgBuilder.buildOptionsResp200(msg);
  	this.send(VRDNIP, Integer.parseInt(RmtPort), o2Msg.toString().getBytes(),false);
  }

  private boolean updateInvite(MyMsg tmp_msg)
  {
    boolean Is_Updated=false;
    
    if(IncInviteMsg == null)
    {
      IncInviteMsg = tmp_msg;
      Is_Updated=true;
    }
    else
    {
      if(! IncInviteMsg.getCallID().equalsIgnoreCase(tmp_msg.getCallID()))
      {
        IncInviteMsg = tmp_msg;
        Is_Updated=true;
      }
    }
    
    return Is_Updated;
  }
  
  

  /**
   * Send a message.
   * a_Address the host name to send the message to.
   * a_Port the port to send the message to.
   * a_ByteArray a ByteArray containing the message to send.
   */
	public String send(String a_Address, int a_Port, byte[] a_ByteArray)
	{
		String result;

		try 
		{
			int ilength = a_ByteArray.length;
			DatagramPacket packet = new DatagramPacket(a_ByteArray, 
														   ilength, 
														   InetAddress.getByName(a_Address),
														   a_Port);
			result = new String( packet.getData() );
  	  Calendar Cc=Calendar.getInstance();
 		  String MyTimestamp=Cc.get(Calendar.YEAR)+"-"+(Cc.get(Calendar.MONTH)+1)+"-"+Cc.get(Calendar.DAY_OF_MONTH)+" "+Cc.get(Calendar.HOUR_OF_DAY)+":"+Cc.get(Calendar.MINUTE)+":"+Cc.get(Calendar.SECOND);
			myOutput(" Packet sent at: "+ MyTimestamp);
//      Method Not Supported.
//			myOutput(" From : " + m_DatagramSocket.getLocalAddress() + " To: " + packet.getSocketAddress());
			myOutput(result);

			m_DatagramSocket.send(packet);
		}
		catch(IOException e)
		{
			result = "Error sending datagram packet " + e;
		}
		return result;
	}
	
	 /**
	 * Send a message.
	 * @param a_Address the host name to send the message to.
	 * @param a_Port the port to send the message to.
	 * @param a_FileName the filename of the message to send.
	 */
	public String send(String a_Address, int a_Port, String a_FileName)
	{
		String result;

		try
		{
			BufferedInputStream buffer = 
				new BufferedInputStream( new FileInputStream(a_FileName) );
			try 
			{
				int ilength = buffer.available();
				byte[] buf = new byte[ilength];
				buffer.read(buf, 0, ilength);
				DatagramPacket packet = new DatagramPacket(buf, 
														   ilength, 
														   InetAddress.getByName(a_Address),
														   a_Port);
				result = new String( packet.getData() );
	  	  Calendar Cc=Calendar.getInstance();
  		  String MyTimestamp=Cc.get(Calendar.YEAR)+"-"+(Cc.get(Calendar.MONTH)+1)+"-"+Cc.get(Calendar.DAY_OF_MONTH)+" "+Cc.get(Calendar.HOUR_OF_DAY)+":"+Cc.get(Calendar.MINUTE)+":"+Cc.get(Calendar.SECOND);
				myOutput(" Packet sent at: "+ MyTimestamp);
// Method getSocketAddress() is supported on JDK1.4 or higher
//			myOutput(" From : " + m_DatagramSocket.getLocalAddress() + " To: " + packet.getSocketAddress());
				myOutput(result);

				buffer.close();
				m_DatagramSocket.send(packet);
			}
			catch(IOException e)
			{
				result = "Error sending datagram packet " + e;
			}
		}
		catch(FileNotFoundException e)
		{
			result = ("Error opening message file " + e);
		}

		
		return result;
	}

  /**
  * Send a message.
  * a_Address the host name to send the message to.
  * a_Port the port to send the message to.
  * a_ByteArray a ByteArray containing the message to send.
  * ShowHint a boolean determine whether there should be any output to 
  *          prompt the user the result of the send operation
  *
  * Notes:   This method is introduced mainly to send the OPTIONS heartbeat
  *          message. In this situation, the ShowHint is always set to false
  *          to allow the OPTIONS heartbeat signal to be sent regularly without
  *          interfering the user interface.
  */
	public String send(String a_Address, int a_Port, byte[] a_ByteArray, boolean ShowHint)
	{
		String result;

		try 
		{
			int ilength = a_ByteArray.length;
			DatagramPacket packet = new DatagramPacket(a_ByteArray, 
														   ilength, 
														   InetAddress.getByName(a_Address),
														   a_Port);
			result = new String( packet.getData() );
			if(ShowHint)
			{
				System.out.println("Preparing to send buffer:");
				System.out.println(result);
			}
			m_DatagramSocket.send(packet);
		}
		catch(IOException e)
		{
			result = "Error sending datagram packet " + e;
		}

		return result;
	}

  
  public static void main(String[] args)
  {
	  String[] Para = new String[5];

 		// Initial the MyMessenger Object to handle the send/receive function
 		MyMessenger MyMessenger = new MyMessenger();
 		MyMessenger.setObserver(MyMessenger);
   		
		Para = parseArguments(args);
    LclIP=Para[0];
    LclPort=Para[1];
    VRDNIP=Para[2];
    RmtPort=Para[3];
    SIPIP=Para[4];

	  MyMessenger.openDatagramSocket(LclIP, Integer.parseInt(LclPort) );

	 	// Initial the Input Handler.
    InputStreamReader isr=new InputStreamReader(System.in);
    BufferedReader br=new BufferedReader(isr);
    MyMessenger.setRunning(true);
    System.out.println("");
    System.out.print("Your Command Please>");

		while(MyMessenger.getRunning())
		{
			try
			{
				CmdLine = br.readLine();
				if(CmdLine.length() > 0)
				{
		  		if(MyMessenger.myParser(CmdLine))
		  			MyMessenger.myCommandHandler();
		  	}
		    System.out.println("");
    		System.out.print("Your Command Please>");
		  }
		  catch (IOException e)
		  {
		  	System.out.println(e);
		  }
		}   		
  }
   
  /**
   * A Parser to extract the command and the parameters(if there is any) from user input
   */
  private boolean myParser(String a_Cmd)
  {
  	StringTokenizer st = new StringTokenizer(a_Cmd);
  	boolean InfoComplete=false;
  	
  	// Retrieve Command
  	if(st.hasMoreTokens())
  	{
  		Cmd = st.nextToken();
  		// Get the file to send.
	  	if(Cmd.equalsIgnoreCase("SendVrdn") || Cmd.equalsIgnoreCase("SV"))
		  {
			  if(st.hasMoreTokens())
  			{
	  			FileToSend = st.nextToken();
		  		InfoComplete = true;
			  }
  			else
	  	 		this.myOutput("Usage: SendVrdn <FileName>");
		  }
	  	// Get the file to send.
	  	else if(Cmd.equalsIgnoreCase("SendSip") || Cmd.equalsIgnoreCase("SS"))
		  {
  			if(st.hasMoreTokens())
	  		{
  				FileToSend = st.nextToken();
		  		InfoComplete = true;
			  }
	  		else
		   		this.myOutput("Usage: SendSip <FileName>");
  		} 
	  	// Get the file to send.
		  else if(Cmd.equalsIgnoreCase("RespondVrdn") || Cmd.equalsIgnoreCase("RV"))
  		{
	  		if(st.hasMoreTokens())
		  	{
			  	FileToSend = st.nextToken();
				  InfoComplete = true;
  			}
	  		else
		   		this.myOutput("Usage: RespondVrdn <FileName>");
  		} 
  		// Get the file to send.
	  	else if(Cmd.equalsIgnoreCase("RespondSip") || Cmd.equalsIgnoreCase("RS"))
		  {
			  if(st.hasMoreTokens())
			  {
  				FileToSend = st.nextToken();
	  			InfoComplete = true;
		  	}
			  else
		 		  this.myOutput("Usage: RespondSip <FileName>");
  		}
	  	else if(Cmd.equalsIgnoreCase("RespondSip100") || Cmd.equalsIgnoreCase("RS100"))
		  {
   			InfoComplete = true;
  		}
	  	else if(Cmd.equalsIgnoreCase("SET"))
		  {
   			if(st.hasMoreTokens())
   			{
   			  FlagToSet=st.nextToken();
     			InfoComplete = true;
   			}
   			else
   			  this.myOutput("Usage: SET <FLAG>");
  		}
  		else if(Cmd.equalsIgnoreCase("TandomSip") || Cmd.equalsIgnoreCase("TS"))
	  	{
		  	if(st.hasMoreTokens())
			  {
				  FileToSend = st.nextToken();
  				InfoComplete = true;
	  		}
		  	else
		 	  	this.myOutput("Usage: TandomSip <FileName>");
  		}
  		else if(Cmd.equalsIgnoreCase("TandomVrdn") || Cmd.equalsIgnoreCase("TV"))
	  	{
		  	if(st.hasMoreTokens())
			  {
				  FileToSend = st.nextToken();
  				InfoComplete = true;
	  		}
		  	else
		 	  	this.myOutput("Usage: TandomVrdn <FileName>");
  		}
  		else if(Cmd.equalsIgnoreCase("Invite") || Cmd.equalsIgnoreCase("Inv"))
	  	{
				InfoComplete = true;
  		}
  		// Get the msg to send.
	  	else if(Cmd.equalsIgnoreCase("MSG"))
		  {
			  String Msg="";
  			if(!st.hasMoreTokens())
	  		{
		   		this.myOutput("Usage: Msg <Msg>");
			  	InfoComplete = false;
  			}
	  		else
		  	{
			  // Use the while loop to allow the space in the msg body.
				  while(st.hasMoreTokens())
  				{
	  				Msg=Msg+" "+st.nextToken();
		  		}	
			  	MsgToSend=Msg;
				  InfoComplete = true;
  			}
	  	}
		  else if(Cmd.equalsIgnoreCase("Debug"))
  		{
	  		String DebugFlag="";
		  	if(!st.hasMoreTokens())
			  {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -