Add TransportUtilities csproj
This commit is contained in:
1 parent
486c314f19
commit
91c2f6f033
17 files changed
+1489
No files matched your search
@@ -0,0 +1,98 @@
|
||||
using System;
|
||||
using BCG.Utilities.Transport.ICMP;
|
||||
using System.Text;
|
||||
|
||||
|
||||
namespace BCG.Utilities.Transport
|
||||
{
|
||||
/// <summary>
|
||||
/// Derive from this class to create your own BluePinger
|
||||
/// </summary>
|
||||
public abstract class BluePingMessenger : StandardMessenger
|
||||
{
|
||||
public BluePingMessenger()
|
||||
{
|
||||
}
|
||||
/// <summary>
|
||||
/// Override this method to return a string that will denote an BluePing Request
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
protected abstract string myGetRequestMessage();
|
||||
/// <summary>
|
||||
/// Override this method to return a string that will denote an BluePing Response
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
protected abstract string myGetResponseMessage();
|
||||
/// <summary>
|
||||
/// A string that will identify a request for an ICMP echo. If it is over
|
||||
/// 32 bytes, it will be truncated
|
||||
/// </summary>
|
||||
public string requestMessage
|
||||
{
|
||||
get
|
||||
{
|
||||
string req = myGetRequestMessage();
|
||||
if(req.Length > packetSize)
|
||||
req = req.Substring(0, packetSize);
|
||||
return req;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// A string that will identify an ICMP echo response. It will be truncated if it is over 32 bytes.
|
||||
/// </summary>
|
||||
public string responseMessage
|
||||
{
|
||||
get
|
||||
{
|
||||
string resp = myGetResponseMessage();
|
||||
if(resp.Length > packetSize)
|
||||
resp = resp.Substring(0, packetSize);
|
||||
return resp;
|
||||
}
|
||||
}
|
||||
|
||||
override public void getRequestData(byte[] data)
|
||||
{
|
||||
string req = requestMessage;
|
||||
for(int i = 0; i < data.Length; i++)
|
||||
{
|
||||
if(i < req.Length)
|
||||
data[i] = Convert.ToByte(req[i]);
|
||||
}
|
||||
}
|
||||
override public void getResponseData(byte[] data, byte[] origPacketReceived, int dataSegOffset)
|
||||
{
|
||||
string resp = responseMessage;
|
||||
for(int i = 0; i < data.Length; i++)
|
||||
{
|
||||
if(i < resp.Length)
|
||||
data[i] = Convert.ToByte(resp[i]);
|
||||
}
|
||||
}
|
||||
override public bool continueVerification(int actualBytesReceived, byte[] sent, byte[] received)
|
||||
{
|
||||
byte[] respData = new byte[packetSize];
|
||||
Array.Copy(received, ipHeaderOffset + headerOffset, respData, 0, packetSize);
|
||||
ASCIIEncoding enc = new ASCIIEncoding();
|
||||
string trueResp = responseMessage;
|
||||
string resp = enc.GetString(respData, 0, trueResp.Length);
|
||||
bool eq = (resp == trueResp);
|
||||
return eq;
|
||||
}
|
||||
override public bool verifyReceivedMessage(byte[] rec)
|
||||
{
|
||||
bool size = (rec.Length == packetSize + headerOffset + ipHeaderOffset);
|
||||
if(size)
|
||||
{
|
||||
byte[] data = new byte[packetSize];
|
||||
Array.Copy(rec, headerOffset + ipHeaderOffset, data, 0, packetSize);
|
||||
string trueReq = requestMessage;
|
||||
string req = new ASCIIEncoding().GetString(data, 0, trueReq.Length);
|
||||
bool eq = (req == trueReq);
|
||||
return eq;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Diagnostics;
|
||||
using BCG.Utilities.Transport;
|
||||
|
||||
namespace BCG.Utilities.Transport.ICMP
|
||||
{
|
||||
public class ICMPHelper : NetworkHelper
|
||||
{
|
||||
public ICMPHelper(IMessenger mess) : base(mess)
|
||||
{
|
||||
}
|
||||
public override Socket createSocket()
|
||||
{
|
||||
return new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
|
||||
}
|
||||
public override Socket configureSocket(int ttl, int receiveTimeoutMilli, int sendTimeoutMilli)
|
||||
{
|
||||
Socket s = createSocket();
|
||||
s.SetSocketOption(SocketOptionLevel.IP,
|
||||
SocketOptionName.IpTimeToLive, ttl);
|
||||
s.SetSocketOption(SocketOptionLevel.Socket,
|
||||
SocketOptionName.SendTimeout,
|
||||
sendTimeoutMilli);
|
||||
s.SetSocketOption(SocketOptionLevel.Socket,
|
||||
SocketOptionName.ReceiveTimeout,
|
||||
receiveTimeoutMilli);
|
||||
//This fucks you up
|
||||
//s.SetSocketOption(SocketOptionLevel.IP,
|
||||
// SocketOptionName.NoDelay, 1);
|
||||
return s;
|
||||
}
|
||||
public override NetMessage createMessage()
|
||||
{
|
||||
return createMessage(null);
|
||||
}
|
||||
/// <summary>
|
||||
/// This method will create an ICMPMessageStructure
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public override NetMessage createMessage(byte[] data)
|
||||
{
|
||||
ICMPHeader ip= new ICMPHeader();
|
||||
ip.type = getRequestType();
|
||||
ip.code = 0;
|
||||
ip.checksum = 0;
|
||||
//somewhat of a unique ID
|
||||
ip.id = (ushort)DateTime.Now.Millisecond;
|
||||
ip.seq = 0;
|
||||
|
||||
ICMPMessage req = new ICMPMessage();
|
||||
req.icmp= ip;
|
||||
|
||||
if(data == null)
|
||||
{
|
||||
req.data = new byte[packetSize];
|
||||
myGetRequestData(req.data);
|
||||
}
|
||||
else
|
||||
req.data = data;
|
||||
return req;
|
||||
}
|
||||
public virtual byte getRequestType()
|
||||
{
|
||||
return ICMPConstants.ICMP_ECHOREQ;
|
||||
}
|
||||
public virtual byte getResponseType()
|
||||
{
|
||||
return ICMPConstants.ICMP_ECHOREPLY;
|
||||
}
|
||||
/// <summary>
|
||||
/// This method bulids an array of bytes from the request struct
|
||||
/// </summary>
|
||||
/// <param name="req"></param>
|
||||
/// <returns></returns>
|
||||
public override byte[] createPacket(NetMessage request)
|
||||
{
|
||||
ICMPMessage req = (ICMPMessage)request;
|
||||
byte[] b = new byte[packetSize + headerOffset];
|
||||
b[0] = req.icmp.type;
|
||||
b[1] = req.icmp.code;
|
||||
Array.Copy(BitConverter.GetBytes(req.icmp.checksum), 0, b, 2, 2);
|
||||
|
||||
Array.Copy(BitConverter.GetBytes(req.icmp.id),
|
||||
0, b, 4, 2);
|
||||
Array.Copy(BitConverter.GetBytes(req.icmp.seq),
|
||||
0, b, 6, 2);
|
||||
for(int i=0; i< req.data.Length; i++)
|
||||
b[i+headerOffset]= req.data[i];
|
||||
|
||||
//calculate checksum
|
||||
int iCheckSum = 0;
|
||||
for (int i= 0; i < b.Length; i+= 2)
|
||||
iCheckSum += Convert.ToInt32( BitConverter.ToUInt16(b,i));
|
||||
|
||||
iCheckSum = (iCheckSum >> 16) + (iCheckSum & 0xffff);
|
||||
iCheckSum += (iCheckSum >> 16);
|
||||
|
||||
//update byte array to reflect checksum
|
||||
Array.Copy(BitConverter.GetBytes((ushort)~iCheckSum), 0,
|
||||
b, 2, 2);
|
||||
return b;
|
||||
}
|
||||
public override byte[] generateResponseMessage(byte[] packetReceived)
|
||||
{
|
||||
if(myVerifyReceivedMessage(packetReceived))
|
||||
{
|
||||
byte[] data = new byte[packetSize];
|
||||
myGetResponseData(data, packetReceived, headerOffset);
|
||||
NetMessage msg = createMessage(data);
|
||||
ICMPMessage imsg = (ICMPMessage)msg;
|
||||
imsg.icmp.type = getResponseType();
|
||||
ushort id = BitConverter.ToUInt16(packetReceived, 24);
|
||||
imsg.icmp.id = id;
|
||||
byte[] pack = createPacket(msg);
|
||||
return pack;
|
||||
}
|
||||
else
|
||||
return null;
|
||||
}
|
||||
public override bool verifyResponseMessage(int actualBytesReceived, byte[] sent, byte[] received)
|
||||
{
|
||||
try
|
||||
{
|
||||
string val = new System.Text.ASCIIEncoding().GetString(received);
|
||||
if((actualBytesReceived == packetSize + headerOffset + ipHeaderOffset) &&
|
||||
//the recieved id is at ipHeaderOffset + 4
|
||||
(BitConverter.ToInt16(received, 24) ==
|
||||
//the sent id is at 4
|
||||
BitConverter.ToInt16(sent,4))&&
|
||||
//the type is now at 20 (it was ICMP_ECHOREQ originally, now it is ICMP_ECHOREPLY)
|
||||
(received[20] == getResponseType()))
|
||||
return myContinueVerification(actualBytesReceived, sent, received);
|
||||
else
|
||||
return false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Diagnostics;
|
||||
|
||||
using BCG.Utilities.Transport;
|
||||
|
||||
namespace BCG.Utilities.Transport.ICMP
|
||||
{
|
||||
//ICMP constants
|
||||
public struct ICMPConstants
|
||||
{
|
||||
public const int ICMP_ERROR = -1;
|
||||
public const int ICMP_ECHOREPLY= 0; // Echo reply query
|
||||
public const int ICMP_TIMEEXCEEDED= 11; // TTL exceeded error
|
||||
public const int ICMP_INFORMATIONREQUEST = 15;
|
||||
public const int ICMP_INFORMATIONREPLY = 16;
|
||||
public const int ICMP_ECHOREQ= 8; // Echo request query
|
||||
public const int MAX_TTL= 256; // Max TTL
|
||||
}
|
||||
|
||||
//ICMP header, size is 8 bytes
|
||||
public struct ICMPHeader
|
||||
{
|
||||
public byte type; // Type
|
||||
public byte code; // Code
|
||||
public ushort checksum; // Checksum
|
||||
public ushort id; // Identification
|
||||
public ushort seq; // Sequence
|
||||
}
|
||||
|
||||
|
||||
// ICMP Echo Request, size is 12+ 32 (PACKET_SIZE as defined in class Trace)= 44 bytes
|
||||
public class ICMPMessage : NetMessage
|
||||
{
|
||||
public ICMPHeader icmp;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using System;
|
||||
|
||||
namespace BCG.Utilities.Transport.ICMP
|
||||
{
|
||||
public class SpecialICMPHelper : ICMPHelper
|
||||
{
|
||||
public SpecialICMPHelper(IMessenger mess) : base(mess)
|
||||
{
|
||||
}
|
||||
public override sealed byte getRequestType()
|
||||
{
|
||||
return ICMPConstants.ICMP_INFORMATIONREQUEST;
|
||||
}
|
||||
public override sealed byte getResponseType()
|
||||
{
|
||||
return ICMPConstants.ICMP_INFORMATIONREPLY;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
|
||||
namespace BCG.Utilities.Transport
|
||||
{
|
||||
public interface IMessenger
|
||||
{
|
||||
void defineData(int packetsz, int headeroff, int ipHeaderoff);
|
||||
|
||||
void getRequestData(byte[] data);
|
||||
void getResponseData(byte[] data, byte[] origPacketReceived, int dataSegOffset);
|
||||
|
||||
bool continueVerification(int actualBytesReceived, byte[] sent, byte[] received);
|
||||
bool verifyReceivedMessage(byte[] rec);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Runtime.Remoting;
|
||||
using System.Runtime.Remoting.Channels;
|
||||
using System.Runtime.Remoting.Messaging;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Runtime.Serialization.Formatters;
|
||||
using System.Runtime.Serialization.Formatters.Binary;
|
||||
using System.Messaging;
|
||||
using System.Collections;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace BCG.Utilities.Transport.MSMQChannel
|
||||
{
|
||||
/// <summary>
|
||||
/// Use this class to send outbound messages from the client side.
|
||||
/// </summary>
|
||||
public class MSMQClientChannel : IChannelSender
|
||||
{
|
||||
// these are a hardcoded default values
|
||||
const int PATH_MINNUMOFFIELDS = 5;
|
||||
public const int DEFAULT_TIMEOUTINSEC = 60;
|
||||
public const string DEFAULT_RESPONDCHANNEL = @".\RspChannel";
|
||||
public const string DEFAULT_ADMINCHANNEL = @".\AdminChannel";
|
||||
public const string DEFAULT_CHANNELNAME = "";
|
||||
public const int DEFAULT_CHANNELPRIORITY = 1;
|
||||
private const string myQPrefix = @".\Private$\";
|
||||
|
||||
//
|
||||
private string myChannelName;
|
||||
private int myChannelPriority;
|
||||
private TimeSpan myResponseTimeOutInSec;
|
||||
private MessageQueue myAdminQueue = null;
|
||||
private MessageQueue myResponseQueue = null;
|
||||
|
||||
#region Constructor
|
||||
// MSMQClientChannel
|
||||
public MSMQClientChannel () : this (DEFAULT_CHANNELNAME, DEFAULT_RESPONDCHANNEL,
|
||||
DEFAULT_ADMINCHANNEL, DEFAULT_TIMEOUTINSEC, DEFAULT_CHANNELPRIORITY) {}
|
||||
|
||||
public MSMQClientChannel (string channelName) : this (channelName, DEFAULT_RESPONDCHANNEL,
|
||||
DEFAULT_ADMINCHANNEL, DEFAULT_TIMEOUTINSEC, DEFAULT_CHANNELPRIORITY) {}
|
||||
|
||||
public MSMQClientChannel (string channelName, string respondQueueName) : this (channelName,
|
||||
respondQueueName, DEFAULT_ADMINCHANNEL, DEFAULT_TIMEOUTINSEC, DEFAULT_CHANNELPRIORITY) {}
|
||||
|
||||
public MSMQClientChannel (string channelName, string respondQueueName, string pathAQ) :
|
||||
this (channelName, respondQueueName, pathAQ, DEFAULT_TIMEOUTINSEC, DEFAULT_CHANNELPRIORITY) {}
|
||||
|
||||
public MSMQClientChannel (string channelName, string respondQueueName, string pathAQ, int timeout) :
|
||||
this (channelName, respondQueueName, pathAQ, timeout, DEFAULT_CHANNELPRIORITY) {}
|
||||
|
||||
public MSMQClientChannel (string channelName, string respondQueueName, string pathAQ,
|
||||
int timeout, int priority)
|
||||
{
|
||||
myInit (channelName, respondQueueName, pathAQ, timeout, priority);
|
||||
}
|
||||
|
||||
public MSMQClientChannel (IDictionary properties, IServerChannelSinkProvider serverSinkProvider)
|
||||
{
|
||||
string respondQueueName = DEFAULT_RESPONDCHANNEL;
|
||||
string pathAQ = null;
|
||||
int timeout = DEFAULT_TIMEOUTINSEC;
|
||||
string channelName = DEFAULT_CHANNELNAME;
|
||||
int channelPriority = DEFAULT_CHANNELPRIORITY;
|
||||
|
||||
// administratively setup the config values (xxx.exe.config file)
|
||||
if (properties.Contains ("name"))
|
||||
channelName = properties["name"].ToString ();
|
||||
|
||||
if (properties.Contains ("priority"))
|
||||
channelPriority = Convert.ToInt32 (properties["priority"]);
|
||||
|
||||
if (properties.Contains ("respond"))
|
||||
respondQueueName = properties["respond"].ToString ();
|
||||
|
||||
if (properties.Contains ("admin"))
|
||||
pathAQ = properties["admin"].ToString ();
|
||||
|
||||
if (properties.Contains ("timeout"))
|
||||
timeout = Convert.ToInt32 (properties["timeout"]);
|
||||
|
||||
myInit(channelName, respondQueueName, pathAQ, timeout, channelPriority);
|
||||
}
|
||||
|
||||
private void myInit (string channelName, string respondQueueName, string pathAQ,
|
||||
int timeout, int priority)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(channelName == null || channelName == string.Empty)
|
||||
myChannelName = DEFAULT_CHANNELNAME;
|
||||
else
|
||||
myChannelName = channelName;
|
||||
myChannelPriority = priority;
|
||||
myResponseTimeOutInSec = new TimeSpan (timeout * TimeSpan.TicksPerSecond);
|
||||
|
||||
// config an admin queue
|
||||
if (pathAQ != null)
|
||||
{
|
||||
myAdminQueue = myGetQueue (pathAQ);
|
||||
myAdminQueue.Formatter = new BinaryMessageFormatter ();
|
||||
}
|
||||
|
||||
// incoming (Response) queue;
|
||||
myResponseQueue = myGetQueue (myQPrefix + respondQueueName);
|
||||
myResponseQueue.Formatter = new BinaryMessageFormatter ();
|
||||
myResponseQueue.MessageReadPropertyFilter.Body = true;
|
||||
myResponseQueue.MessageReadPropertyFilter.CorrelationId = true;
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
Debug.Assert(false, "MSMQClientChannel Error: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private MessageQueue myGetQueue (string path)
|
||||
{
|
||||
MessageQueue mq = null;
|
||||
if (!MessageQueue.Exists (path))
|
||||
mq = MessageQueue.Create (path);
|
||||
else
|
||||
mq = new MessageQueue (path);
|
||||
return mq;
|
||||
}
|
||||
#endregion
|
||||
|
||||
// access to the private members
|
||||
public MessageQueue responseQueue
|
||||
{
|
||||
get { return myResponseQueue; }
|
||||
set {}
|
||||
}
|
||||
|
||||
public MessageQueue adminQueue
|
||||
{
|
||||
get { return myAdminQueue; }
|
||||
set {}
|
||||
}
|
||||
|
||||
public TimeSpan responseTimeOut
|
||||
{
|
||||
get { return myResponseTimeOutInSec; }
|
||||
set {}
|
||||
}
|
||||
|
||||
#region IChannel Members
|
||||
public string ChannelName
|
||||
{
|
||||
get { return myChannelName; }
|
||||
set {}
|
||||
}
|
||||
|
||||
public int ChannelPriority
|
||||
{
|
||||
get { return myChannelPriority; }
|
||||
set {}
|
||||
}
|
||||
|
||||
public string Parse (string url, out string objectURI)
|
||||
{
|
||||
return objectURI = null;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region IChannelSender Members
|
||||
/// <summary>
|
||||
/// When consumer of the remote object calling the Activator class, the call is
|
||||
/// forward to the CreateMessageSink() to check if the specified URL can be handled
|
||||
/// by this channel. If the channel name is not matching with the URL field address,
|
||||
/// then null is returned. The process is repeated through all registered channels
|
||||
/// until a successful match is found, otherwise the error exception is thrown. In
|
||||
/// the successful case, the MSMQMessageSink class is instated and its reference
|
||||
/// is returned to the caller.
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="data"></param>
|
||||
/// <param name="objectURI"></param>
|
||||
/// <returns></returns>
|
||||
//URL = msmq://ip/qname/uri
|
||||
public virtual IMessageSink CreateMessageSink (String url, Object data, out string objectURI)
|
||||
{
|
||||
objectURI = null;
|
||||
try
|
||||
{
|
||||
string[] s = url.Split (new Char[]{'/'} );
|
||||
|
||||
//if(s.Length < PATH_MINNUMOFFIELDS || myChannelName + ":" != s[0])
|
||||
if(s.Length < PATH_MINNUMOFFIELDS || !myVerifyProtocol(s[0]))
|
||||
return null; // this is not correct channel
|
||||
|
||||
string outpath = "";
|
||||
for (int ii = 2; ii < s.Length-1; ii++)
|
||||
{
|
||||
if(s[ii].ToUpper() != "PRIVATE$")
|
||||
{
|
||||
outpath += s[ii];
|
||||
outpath += "\\";
|
||||
}
|
||||
}
|
||||
outpath = outpath.TrimEnd (new Char[]{'\\'});
|
||||
outpath = "FormatName:DIRECT=TCP:" + outpath;
|
||||
int i = outpath.IndexOf("\\");
|
||||
if(i == -1)
|
||||
throw new ArgumentException("Server URL is Invalid!");
|
||||
outpath = outpath.Insert(i, @"\Private$");
|
||||
objectURI = s[s.Length - 1];
|
||||
|
||||
MSMQMessageSink msgsink = new MSMQMessageSink(this, objectURI, outpath);
|
||||
return msgsink;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
private bool myVerifyProtocol(string prot)
|
||||
{
|
||||
return (prot.ToUpper() == "MSMQ:");
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
using System;
|
||||
using System.Runtime.Remoting.Messaging;
|
||||
using System.Collections;
|
||||
using System.Messaging;
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
|
||||
namespace BCG.Utilities.Transport.MSMQChannel
|
||||
{
|
||||
/// <summary>
|
||||
/// The MSMQMessageSink is derived class from the IMessageSink and IDictionary
|
||||
/// interfaces. When a method call is made on the proxy, the remoting infrastructure
|
||||
/// passing IMessage object to this class using SyncProcessMessage () or
|
||||
/// AsyncProcessMessage ().
|
||||
/// </summary>
|
||||
public class MSMQMessageSink : IMessageSink, IDictionary
|
||||
{
|
||||
private const string OBJECTURI = "__objectUri";
|
||||
private MSMQClientChannel mySender = null;
|
||||
private MessageQueue myOutQueue = null;
|
||||
private string myObjectURI;
|
||||
|
||||
public MSMQMessageSink (MSMQClientChannel sender, string objuri, string outpath)
|
||||
{
|
||||
try
|
||||
{
|
||||
mySender = sender;
|
||||
myObjectURI = objuri;
|
||||
|
||||
// construct an outgoing queue for the sync or async Calls
|
||||
myOutQueue = new MessageQueue (outpath);
|
||||
myOutQueue.Formatter = new BinaryMessageFormatter ();
|
||||
myOutQueue.DefaultPropertiesToSend.AdministrationQueue = mySender.adminQueue;
|
||||
myOutQueue.DefaultPropertiesToSend.AcknowledgeType = AcknowledgeTypes.NegativeReceive;
|
||||
myOutQueue.DefaultPropertiesToSend.TimeToBeReceived = mySender.responseTimeOut;
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
Debug.Assert(false, "MSMQMessageSink Init Error: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private Message mySendRequestMessage(IMessage msgReq)
|
||||
{
|
||||
Message outMsg = null;
|
||||
try
|
||||
{
|
||||
//one thread can build a message at a time.
|
||||
string label = "";
|
||||
lock(myOutQueue)
|
||||
{
|
||||
msgReq.Properties[OBJECTURI] = myObjectURI;
|
||||
|
||||
// send a remoting message
|
||||
outMsg = new Message(msgReq, new BinaryMessageFormatter ()); // create a message
|
||||
outMsg.ResponseQueue = mySender.responseQueue; // set response queue
|
||||
outMsg.TimeToBeReceived = Message.InfiniteTimeout; // timeout to pick-up a message
|
||||
// outMsg.AcknowledgeType = AcknowledgeTypes.NegativeReceive;
|
||||
// outMsg.AdministrationQueue = mySender.AdminQueue;
|
||||
|
||||
label = msgReq.Properties["__TypeName"] + "." + msgReq.Properties["__MethodName"];
|
||||
}
|
||||
myOutQueue.Send(outMsg, label);
|
||||
System.Threading.Thread.Sleep(0);
|
||||
}
|
||||
catch (MessageQueueException e)
|
||||
{
|
||||
Debug.Assert(false, "MSMQMessageSink SendMessage Error: " + e.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
myOutQueue.Close();
|
||||
}
|
||||
return outMsg;
|
||||
}
|
||||
/// <summary>
|
||||
/// The IMessage object is first serialized by a BinaryMessageFormater into the
|
||||
/// body of the message queue. Before sending a message to the queue, its properties
|
||||
/// are setup for a callback (respond) message. Each outgoing MSMQ message has a
|
||||
/// unique ID, which is used as a key to get a callback message from the Respond queue.
|
||||
/// So, the Sender is waiting for this message infinite timeout, thus blocking the
|
||||
/// caller thread. When the return message is received, it's body is deserialized
|
||||
/// into an IMessage object and returned back to the caller of SyncProcessMessage().
|
||||
/// </summary>
|
||||
/// <param name="msgReq"></param>
|
||||
/// <returns></returns>
|
||||
public virtual IMessage SyncProcessMessage (IMessage msgReq)
|
||||
{
|
||||
IMessage msgRsp = null;
|
||||
try
|
||||
{
|
||||
Message outMsg = mySendRequestMessage(msgReq);
|
||||
MethodCallAnalyzer an = new MethodCallAnalyzer(msgReq);
|
||||
if(!an.hasAttribute(typeof(MSMQOneWayAttribute)))
|
||||
msgRsp = myReceiveReturnMessage (outMsg.Id);
|
||||
}
|
||||
catch (MessageQueueException e)
|
||||
{
|
||||
Console.WriteLine (e.Message);
|
||||
Debug.Assert(false, "MSMQMessageSink SyncProcessMessage Error: " + e.Message);
|
||||
}
|
||||
return msgRsp;
|
||||
}
|
||||
|
||||
private IMessage myReceiveReturnMessage (string id)
|
||||
{
|
||||
lock(this)
|
||||
{
|
||||
MessageQueue respQ = new MessageQueue (mySender.responseQueue.Path);
|
||||
respQ.Formatter = new BinaryMessageFormatter ();
|
||||
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
respQ.MessageReadPropertyFilter.Body = true;
|
||||
respQ.MessageReadPropertyFilter.CorrelationId = true;
|
||||
|
||||
Message msg = respQ.ReceiveByCorrelationId (id, mySender.responseTimeOut);
|
||||
IMessage msgRsp = msg.Body as IMessage;
|
||||
respQ.Close ();
|
||||
return msgRsp;
|
||||
}
|
||||
catch (MessageQueueException e)
|
||||
{
|
||||
if (e.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Both arguments are delegated to the worker thread using the
|
||||
/// BeginInvoke/EndInvoke design pattern and the call is immediately returned to
|
||||
/// the caller with an IMessageCtrl value set to null (you can't abort an active
|
||||
/// async call using the IMessageCtrl object).
|
||||
/// </summary>
|
||||
/// <param name="msgReq"></param>
|
||||
/// <param name="replySink"></param>
|
||||
/// <returns></returns>
|
||||
public virtual IMessageCtrl AsyncProcessMessage(IMessage msgReq, IMessageSink replySink)
|
||||
{
|
||||
HandleAsyncDelegate del = new HandleAsyncDelegate(myHandleAsync);
|
||||
del.BeginInvoke(msgReq, replySink, null, null);
|
||||
return null;
|
||||
}
|
||||
|
||||
private delegate void HandleAsyncDelegate(IMessage msgReq, IMessageSink replySink);
|
||||
// handler of the AsyncProcessMessage worker
|
||||
/// First call SyncProcessMessage() to obtain an IMessage object from the remote
|
||||
/// method. Then, update the AsyncResult object state with this IMessage object.
|
||||
/// Calling replySink.SyncProcessMessage() achieves two objectives: update an
|
||||
/// AsyncResult shared object state by the IMessage object, and set an
|
||||
/// AsyncResult.ManualResetEvent object to notify the async caller that the
|
||||
/// result of the async call can be retrieved using the EndInvoke function.
|
||||
|
||||
private void myHandleAsync(IMessage msgReq, IMessageSink replySink)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(replySink != null)
|
||||
{
|
||||
AsyncResult ar = replySink.NextSink as AsyncResult;
|
||||
// call Remote Method and wait for its Return Value
|
||||
IMessage msgRsp = SyncProcessMessage(msgReq);
|
||||
// update AsyncResult state (_replyMsg, IsCompleted, waitstate, etc.)
|
||||
replySink.SyncProcessMessage(msgRsp);
|
||||
}
|
||||
else
|
||||
{
|
||||
//this is a one way method, we don't need to hang around and wait for a return
|
||||
mySendRequestMessage(msgReq);
|
||||
}
|
||||
}
|
||||
catch{}
|
||||
}
|
||||
|
||||
#region IDictionary
|
||||
public virtual IMessageSink NextSink { get { return null; } }
|
||||
public virtual bool Contains(Object key) { return false; }
|
||||
public virtual void Add(Object key, Object value){}
|
||||
public virtual void Remove(Object key){}
|
||||
public virtual void Clear() {}
|
||||
public virtual IDictionaryEnumerator GetEnumerator() { return null; }
|
||||
IEnumerator IEnumerable.GetEnumerator() { return null; }
|
||||
public int Count { get { return 0; }}
|
||||
public void CopyTo(Array array, int index){}
|
||||
public ICollection Keys { get { return null; }}
|
||||
public ICollection Values { get { return null; }}
|
||||
public Object SyncRoot { get { return null; }}
|
||||
public bool IsReadOnly { get { return true; }}
|
||||
public bool IsFixedSize { get { return true; }}
|
||||
public bool IsSynchronized { get { return true; }}
|
||||
public Object this[Object key] { get { return null; } set {} }
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System;
|
||||
|
||||
namespace BCG.Utilities.Transport.MSMQChannel
|
||||
{
|
||||
[AttributeUsage (AttributeTargets.Method)]
|
||||
public class MSMQOneWayAttribute : Attribute
|
||||
{
|
||||
public MSMQOneWayAttribute() : base()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Collections;
|
||||
using System.Messaging;
|
||||
using System.Runtime.Remoting.Channels;
|
||||
using System.Runtime.Remoting.Messaging;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace BCG.Utilities.Transport.MSMQChannel
|
||||
{
|
||||
// Listener
|
||||
public class MSMQServerChannel : IChannelReceiver
|
||||
{
|
||||
// these are a hardcoded default values
|
||||
const string OBJECTURI = "__objectUri";
|
||||
public const string DEFAULT_REQCHANNEL = @".\ReqChannel";
|
||||
public const string DEFAULT_CHANNELNAME = "";
|
||||
public const int DEFAULT_CHANNELPRIORITY = 1;
|
||||
|
||||
private string myChannelName;
|
||||
private int myChannelPriority;
|
||||
private string myURL = string.Empty;
|
||||
private MessageQueue myReceiveQ = null;
|
||||
private const string myQPrefix = @".\Private$\";
|
||||
|
||||
// MSMQServerChannel
|
||||
public MSMQServerChannel () :
|
||||
this (DEFAULT_CHANNELNAME, DEFAULT_REQCHANNEL, DEFAULT_CHANNELPRIORITY)
|
||||
{}
|
||||
|
||||
public MSMQServerChannel (string channelName, string receiveQueueName, int priority)
|
||||
{
|
||||
myInit (channelName, receiveQueueName, priority);
|
||||
}
|
||||
|
||||
public MSMQServerChannel (IDictionary properties, IServerChannelSinkProvider serverSinkProvider)
|
||||
{
|
||||
string channelName = DEFAULT_CHANNELNAME;
|
||||
string listenerPath = DEFAULT_REQCHANNEL;
|
||||
int channelPriority = DEFAULT_CHANNELPRIORITY;
|
||||
|
||||
// administratively setup the config values (xxx.exe.config file)
|
||||
if(properties.Contains("listener"))
|
||||
listenerPath = properties["listener"].ToString();
|
||||
if(properties.Contains("name"))
|
||||
channelName = properties["name"].ToString();
|
||||
if(properties.Contains("priority"))
|
||||
channelPriority = Convert.ToInt32(properties["priority"]);
|
||||
|
||||
myInit (channelName, listenerPath, channelPriority);
|
||||
}
|
||||
|
||||
private void myInit (string channelName, string receiveQueueName, int priority)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(channelName == null || channelName == string.Empty)
|
||||
myChannelName = DEFAULT_CHANNELNAME;
|
||||
else
|
||||
myChannelName = channelName;
|
||||
myChannelPriority = priority;
|
||||
Debug.Assert (receiveQueueName != string.Empty);
|
||||
|
||||
//open Listener queue
|
||||
if (MessageQueue.Exists (myQPrefix + receiveQueueName))
|
||||
myReceiveQ = new MessageQueue (myQPrefix + receiveQueueName);
|
||||
else
|
||||
myReceiveQ = MessageQueue.Create (myQPrefix + receiveQueueName);
|
||||
|
||||
myReceiveQ.Formatter = new BinaryMessageFormatter();
|
||||
myReceiveQ.MessageReadPropertyFilter.AcknowledgeType = true;
|
||||
myReceiveQ.MessageReadPropertyFilter.TimeToBeReceived = true;
|
||||
myReceiveQ.MessageReadPropertyFilter.CorrelationId = true;
|
||||
|
||||
// create url
|
||||
string ip = BCG.Utilities.General.SysInfoManager.getIPSWMI()[0];
|
||||
myURL = @"msmq://" + ip + @"/" + (myQPrefix.Replace("\\", "/")).Replace(@"./","") + receiveQueueName;
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
Debug.Assert(false, "MSMQServerChannel Init Error: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
#region IChannel Memebers
|
||||
public string ChannelName
|
||||
{
|
||||
get { return myChannelName; }
|
||||
}
|
||||
|
||||
public int ChannelPriority
|
||||
{
|
||||
get { return myChannelPriority; }
|
||||
}
|
||||
|
||||
public string Parse (string url, out string objectURI)
|
||||
{
|
||||
objectURI = null;
|
||||
return url;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region IChannelReceiver Memebers
|
||||
private bool myIsListening = false;
|
||||
private Thread myListener = null;
|
||||
|
||||
public object ChannelData
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!myIsListening)
|
||||
{
|
||||
StartListening (null);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public virtual string[] GetUrlsForUri (string objectURI)
|
||||
{
|
||||
return new string[] { myURL + "/" + objectURI };
|
||||
}
|
||||
|
||||
|
||||
public virtual void StopListening (object data)
|
||||
{
|
||||
if (myListener != null)
|
||||
{
|
||||
lock(this)
|
||||
{
|
||||
try
|
||||
{
|
||||
myListener.Abort ();
|
||||
myReceiveQ.Close ();
|
||||
myListener.Join (5000);
|
||||
myIsListening = false;
|
||||
}
|
||||
catch(ThreadAbortException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public virtual void StartListening (object data)
|
||||
{
|
||||
if(!myIsListening)
|
||||
{
|
||||
lock(this)
|
||||
{
|
||||
myListener = new Thread (new ThreadStart (this.myRun));
|
||||
myIsListening = true;
|
||||
myListener.Start ();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void myRun ()
|
||||
{
|
||||
Thread.CurrentThread.IsBackground = true;
|
||||
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
lock(this)
|
||||
{
|
||||
// Wait for client's call
|
||||
//since this is done on another thread, no one will care if we block continually
|
||||
Message msg = myReceiveQ.Receive (MessageQueue.InfiniteTimeout);
|
||||
IMessage msgReq = msg.Body as IMessage;
|
||||
msgReq.Properties["__Uri"] = msgReq.Properties[OBJECTURI]; // work around!!!
|
||||
|
||||
// Dispatch message to the remoting object
|
||||
IMessage msgRsp = ChannelServices.SyncDispatchMessage(msgReq);
|
||||
// update this msg with the return value and send it back to the caller
|
||||
msg.BodyStream.Close (); // clean-up
|
||||
//see if this is a MSMQOneWay method. If it is, we shouldn't send the response
|
||||
MethodCallAnalyzer an = new MethodCallAnalyzer(msgReq);
|
||||
if(!an.hasAttribute(typeof(MSMQOneWayAttribute)))
|
||||
{
|
||||
msg.Body = msgRsp; // serialize IMessage
|
||||
msg.CorrelationId = msg.Id; // cookie
|
||||
try
|
||||
{
|
||||
msg.ResponseQueue.Send (msg, "RET: " + msg.Label); // send message
|
||||
msg.ResponseQueue.Close ();
|
||||
}
|
||||
//if the client is no longer alive, we don't want to send him a message back.
|
||||
catch(ObjectDisposedException)
|
||||
{}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (MessageQueueException e)
|
||||
{
|
||||
if (e.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
|
||||
Debug.Assert(false, "MSMQServerChannel Recieve Error: " + e.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Runtime.Remoting.Messaging;
|
||||
using System.Reflection;
|
||||
|
||||
namespace BCG.Utilities.Transport.MSMQChannel
|
||||
{
|
||||
public class MethodCallAnalyzer
|
||||
{
|
||||
private IMessage myMsg;
|
||||
public MethodCallAnalyzer(IMessage msg)
|
||||
{
|
||||
myMsg = msg;
|
||||
}
|
||||
public bool hasAttribute(Type attributeType)
|
||||
{
|
||||
if(attributeType.IsSubclassOf(typeof(Attribute)))
|
||||
{
|
||||
//The IMessage could come in as a method call object
|
||||
try
|
||||
{
|
||||
MethodCall mc = (MethodCall)myMsg;
|
||||
return mc.MethodBase.IsDefined(attributeType, true);
|
||||
}
|
||||
catch{}
|
||||
//or some other non public class with a property of MethodBase
|
||||
try
|
||||
{
|
||||
//a blatant subversion of encapsulation
|
||||
PropertyInfo pi = myMsg.GetType().GetProperty("MethodBase");
|
||||
object mb = pi.GetValue(myMsg, BindingFlags.GetProperty,
|
||||
null, new object[0], null);
|
||||
MethodBase mbase = (MethodBase)mb;
|
||||
return mbase.IsDefined(attributeType, true);
|
||||
}
|
||||
catch{}
|
||||
return false;
|
||||
}
|
||||
else
|
||||
throw new ArgumentException("Must pass in a Type derived from System.Attribute");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using System;
|
||||
|
||||
namespace BCG.Utilities.Transport
|
||||
{
|
||||
public class NetMessage
|
||||
{
|
||||
public byte[] data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Diagnostics;
|
||||
|
||||
using BCG.Utilities.General;
|
||||
|
||||
namespace BCG.Utilities.Transport
|
||||
{
|
||||
public abstract class NetworkHelper
|
||||
{
|
||||
private IMessenger myDataGen;
|
||||
public NetworkHelper(IMessenger gen)
|
||||
{
|
||||
myDataGen = gen;
|
||||
myDataGen.defineData(packetSize, headerOffset, ipHeaderOffset);
|
||||
}
|
||||
virtual public int ipHeaderOffset
|
||||
{
|
||||
get{return 20;}
|
||||
}
|
||||
virtual public int packetSize
|
||||
{
|
||||
get{return 32;}
|
||||
}
|
||||
virtual public int headerOffset
|
||||
{
|
||||
get{return 8;}
|
||||
}
|
||||
public IPEndPoint createLocalEndPoint(int port)
|
||||
{
|
||||
string[] ips = SysInfoManager.getIPSWMI();
|
||||
Debug.Assert(ips.Length > 0);
|
||||
return new IPEndPoint(IPAddress.Parse(ips[0]), port);
|
||||
}
|
||||
public void trimReceived(ref byte[] rec, int actualBytesReceived)
|
||||
{
|
||||
if(actualBytesReceived > rec.Length || actualBytesReceived <= 0)
|
||||
return;
|
||||
byte[] newBytes = new byte[actualBytesReceived];
|
||||
for(int i = 0; i < actualBytesReceived; i++)
|
||||
{
|
||||
newBytes[i] = rec[i];
|
||||
}
|
||||
rec = newBytes;
|
||||
}
|
||||
public abstract Socket createSocket();
|
||||
public abstract Socket configureSocket(int ttl, int receiveTimeoutMilli, int sendTimeoutMilli);
|
||||
public abstract NetMessage createMessage();
|
||||
public abstract NetMessage createMessage(byte[] data);
|
||||
public abstract byte[] createPacket(NetMessage req);
|
||||
|
||||
protected void myGetRequestData(byte[] data)
|
||||
{
|
||||
myDataGen.getRequestData(data);
|
||||
}
|
||||
protected bool myVerifyReceivedMessage(byte[] rec)
|
||||
{
|
||||
return myDataGen.verifyReceivedMessage(rec);
|
||||
}
|
||||
protected bool myContinueVerification(int actualBytesReceived, byte[] sent, byte[] received)
|
||||
{
|
||||
return myDataGen.continueVerification(actualBytesReceived, sent, received);
|
||||
}
|
||||
protected void myGetResponseData(byte[] data, byte[] origPacketReceived, int dataSegOffset)
|
||||
{
|
||||
myDataGen.getResponseData(data, origPacketReceived, dataSegOffset);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// This method will verify that the response message that you receive is a valid response to
|
||||
/// the request that you have sent. This method allows us to filter standard ICMP traffic
|
||||
/// </summary>
|
||||
/// <param name="actualBytesReceived">How many bytes were actually received</param>
|
||||
/// <param name="sent">The message that was sent</param>
|
||||
/// <param name="received">The message that was recieved</param>
|
||||
/// <returns>True if the response is valid, false if it isn't</returns>
|
||||
abstract public bool verifyResponseMessage(int actualBytesReceived, byte[] sent, byte[] received);
|
||||
/// <summary>
|
||||
/// This method generates a response message to the request
|
||||
/// </summary>
|
||||
/// <param name="packetReceived"></param>
|
||||
/// <returns></returns>
|
||||
abstract public byte[] generateResponseMessage(byte[] packetReceived);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Diagnostics;
|
||||
using BCG.Utilities.Transport.ICMP;
|
||||
|
||||
namespace BCG.Utilities.Transport
|
||||
{
|
||||
public class PingListener
|
||||
{
|
||||
private int myReceivePort;
|
||||
private bool myStop = false;
|
||||
private bool myIsStopped = true;
|
||||
private NetworkHelper myHelper;
|
||||
private Socket mySock;
|
||||
private IPEndPoint myLocalEndPoint;
|
||||
public PingListener(int receivePort, NetworkHelper help)
|
||||
{
|
||||
myReceivePort = receivePort;
|
||||
myHelper = help;
|
||||
mySetup();
|
||||
}
|
||||
public PingListener(int port) : this(port, new ICMPHelper(new StandardMessenger()))
|
||||
{
|
||||
}
|
||||
~PingListener()
|
||||
{
|
||||
mySock.Close();
|
||||
}
|
||||
|
||||
private void mySetup()
|
||||
{
|
||||
try
|
||||
{
|
||||
mySock = myHelper.configureSocket(100, 1000, 1000);
|
||||
myLocalEndPoint = (IPEndPoint) myHelper.createLocalEndPoint(myReceivePort);
|
||||
mySock.Bind(myLocalEndPoint);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
Debug.Assert(false, e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Start listening for ICMP Requests
|
||||
/// </summary>
|
||||
public void beginListening()
|
||||
{
|
||||
myIsStopped = false;
|
||||
new ListenerDelegate(myListen).BeginInvoke(null, null);
|
||||
}
|
||||
/// <summary>
|
||||
/// Stop Listening for ICMP Requests, does not block.
|
||||
/// </summary>
|
||||
public void beginStopListening()
|
||||
{
|
||||
myStop = true;
|
||||
}
|
||||
/// <summary>
|
||||
/// Stop Listening for ICMP Requests, blocks until we actually stop.
|
||||
/// </summary>
|
||||
public void stopListening()
|
||||
{
|
||||
myStop = true;
|
||||
while(!myIsStopped)
|
||||
System.Threading.Thread.Sleep(10);
|
||||
}
|
||||
delegate void ListenerDelegate();
|
||||
private void myListen()
|
||||
{
|
||||
while(!myStop)
|
||||
{
|
||||
try
|
||||
{
|
||||
System.Threading.Thread.Sleep(10);
|
||||
byte[] rec = new byte[256];
|
||||
EndPoint ep = new IPEndPoint(myLocalEndPoint.Address, myLocalEndPoint.Port);
|
||||
int recd = SocketHelper.receivePacket(mySock, ref ep, rec, 1);
|
||||
if(recd > 0)
|
||||
{
|
||||
myHelper.trimReceived(ref rec, recd);
|
||||
byte[] resp = myHelper.generateResponseMessage(rec);
|
||||
if(resp != null)
|
||||
{
|
||||
Console.WriteLine("Replying to ICMP Message from: " + ((IPEndPoint)ep).Address.ToString());
|
||||
((IPEndPoint)ep).Port = myReceivePort;
|
||||
SocketHelper.sendPacket(mySock, ep, resp, 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
Console.WriteLine("EXCEPTION: " + e.GetType().Name + ", " + e.Message);
|
||||
}
|
||||
}
|
||||
myIsStopped = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Diagnostics;
|
||||
|
||||
using BCG.Utilities.Transport.ICMP;
|
||||
|
||||
namespace BCG.Utilities.Transport
|
||||
{
|
||||
public class Pinger
|
||||
{
|
||||
private NetworkHelper myHelper;
|
||||
private int myTTL = 100;
|
||||
private int myRetries;
|
||||
private Socket myPingSock;
|
||||
private IPEndPoint myDest;
|
||||
private IPEndPoint mySrc;
|
||||
private TimeSpan myTimeout;
|
||||
public Pinger(IPAddress host, int pingport, NetworkHelper gen, TimeSpan totalTimeout, int retries)
|
||||
{
|
||||
myHelper = gen;
|
||||
mySetupDestination(host, pingport);
|
||||
mySrc = myHelper.createLocalEndPoint(pingport);
|
||||
myTimeout = totalTimeout;
|
||||
myRetries = retries;
|
||||
mySetupSockets();
|
||||
}
|
||||
private void mySetupDestination(IPAddress host, int port)
|
||||
{
|
||||
if (host == IPAddress.Loopback)
|
||||
{
|
||||
myDest = myHelper.createLocalEndPoint(port);
|
||||
}
|
||||
else
|
||||
myDest = new IPEndPoint(host, port);
|
||||
}
|
||||
public Pinger(IPAddress host, int pingport) : this(host, pingport,
|
||||
new ICMPHelper(new StandardMessenger()), new TimeSpan(0,0,0,5,0), 2)
|
||||
{
|
||||
}
|
||||
~Pinger()
|
||||
{
|
||||
myPingSock.Close();
|
||||
}
|
||||
/// <summary>
|
||||
/// Tries to "ping" a listener on the port specified in the constructor for a period of timeout.
|
||||
/// If there is no response within the timeout period, false will be returned, else true
|
||||
/// This method can throw exceptions
|
||||
/// </summary>
|
||||
/// <returns>Boolean indicating whether a response was received in the timeout period</returns>
|
||||
public bool ping()
|
||||
{
|
||||
NetMessage req = myHelper.createMessage();
|
||||
byte[] toSend = myHelper.createPacket(req);
|
||||
|
||||
bool sent = mySendPacket(toSend);
|
||||
bool received = false;
|
||||
if(sent)
|
||||
{
|
||||
received = myReceivePacket(toSend);
|
||||
}
|
||||
return sent && received;
|
||||
}
|
||||
private void mySetupSockets()
|
||||
{
|
||||
try
|
||||
{
|
||||
int sendTimeout = Convert.ToInt32(myTimeout.TotalMilliseconds/(2*myRetries));
|
||||
int recTimeout = Convert.ToInt32(myTimeout.TotalMilliseconds/(2*myRetries));
|
||||
myPingSock = myHelper.configureSocket(myTTL, recTimeout, sendTimeout);
|
||||
//myPingSock.Bind(mySrc);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
Debug.Assert(false, e.Message);
|
||||
}
|
||||
}
|
||||
private bool myReceivePacket(byte[] sent)
|
||||
{
|
||||
int recd = 1;
|
||||
while(recd > 0)
|
||||
{
|
||||
EndPoint ep = new IPEndPoint(mySrc.Address, mySrc.Port);
|
||||
byte[] rec = new byte[256];
|
||||
recd = SocketHelper.receivePacket(myPingSock, ref ep, rec, 1);
|
||||
myHelper.trimReceived(ref rec, recd);
|
||||
bool valid = myHelper.verifyResponseMessage(recd, sent, rec);
|
||||
if(valid)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
private bool mySendPacket(byte[] send)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SocketHelper.sendPacket(myPingSock, myDest, send, myRetries);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
Exception e1 = e;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Diagnostics;
|
||||
|
||||
|
||||
namespace BCG.Utilities.Transport
|
||||
{
|
||||
public class SocketHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Send a packet on a disconnected and configured socket
|
||||
/// </summary>
|
||||
/// <param name="s">The socket</param>
|
||||
/// <param name="dest">The destination</param>
|
||||
/// <param name="packet">The packet</param>
|
||||
/// <param name="retries">How many times to retry</param>
|
||||
/// <returns>True if successful, False if not</returns>
|
||||
public static bool sendPacket(Socket s, EndPoint dest, byte[] packet, int retries)
|
||||
{
|
||||
if(s.Connected)
|
||||
return false;
|
||||
int ret = 0;
|
||||
for(int i = 0; i < retries; i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
//assuming that ret will return ICMPConstants.ICMP_ERROR if a timeout occurs
|
||||
ret = s.SendTo(packet, packet.Length, SocketFlags.None, dest);
|
||||
if(ret != packet.Length)
|
||||
throw new Exception();
|
||||
else
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/// <summary>
|
||||
/// Recieves a packet on a disconnected and configured socket
|
||||
/// </summary>
|
||||
/// <param name="s">The Socket</param>
|
||||
/// <param name="orig">The origination Point of the send (localhost) Will be filled with the Address of the sender</param>
|
||||
/// <param name="packet">A new'd byte array to recieve</param>
|
||||
/// <param name="retries">How many times to retry</param>
|
||||
/// <returns>Number of bytes received</returns>
|
||||
public static int receivePacket(Socket s, ref EndPoint src, byte[] packet, int retries)
|
||||
{
|
||||
if(s.Connected)
|
||||
return -1;
|
||||
int ret = 0;
|
||||
for(int i = 0; i < retries; i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
ret = s.ReceiveFrom(packet, packet.Length, SocketFlags.None, ref src);
|
||||
if(ret > 0)
|
||||
return ret;
|
||||
else
|
||||
throw new Exception();
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
Exception e1 = e;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
/// <summary>
|
||||
/// Recieve a packet from a connected and configured socket
|
||||
/// </summary>
|
||||
/// <param name="s">The socket</param>
|
||||
/// <param name="packet">A new'd byte array</param>
|
||||
/// <param name="retries">How many times should we retry</param>
|
||||
/// <returns>Number of bytes received</returns>
|
||||
public static int receivePacket(Socket s, byte[] packet, int retries)
|
||||
{
|
||||
if(!s.Connected)
|
||||
return -1;
|
||||
int ret = 0;
|
||||
for(int i = 0; i < retries; i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
ret = s.Receive(packet, packet.Length, SocketFlags.None);
|
||||
if(ret > 0)
|
||||
return ret;
|
||||
else
|
||||
throw new Exception();
|
||||
}
|
||||
catch
|
||||
{}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Send a packet on a connected and configured socket
|
||||
/// </summary>
|
||||
/// <param name="s">The socket</param>
|
||||
/// <param name="packet">The packet to send</param>
|
||||
/// <param name="retries">How many times to retry</param>
|
||||
/// <returns>True if Sent, False if not</returns>
|
||||
public static bool sendPacket(Socket s, byte[] packet, int retries)
|
||||
{
|
||||
if(!s.Connected)
|
||||
return false;
|
||||
int ret = 0;
|
||||
for(int i = 0; i < retries; i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
//assuming that ret will return ICMPConstants.ICMP_ERROR if a timeout occurs
|
||||
ret = s.Send(packet, packet.Length, SocketFlags.None);
|
||||
if(ret != packet.Length)
|
||||
throw new Exception();
|
||||
else
|
||||
return true;;
|
||||
}
|
||||
catch
|
||||
{}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
|
||||
namespace BCG.Utilities.Transport
|
||||
{
|
||||
public class StandardMessenger : IMessenger
|
||||
{
|
||||
public int packetSize, headerOffset, ipHeaderOffset;
|
||||
public StandardMessenger()
|
||||
{
|
||||
}
|
||||
public void defineData(int packetsz, int headeroff, int ipHeaderoff)
|
||||
{
|
||||
packetSize = packetsz;
|
||||
headerOffset = headeroff;
|
||||
ipHeaderOffset = ipHeaderoff;
|
||||
}
|
||||
virtual public void getRequestData(byte[] data)
|
||||
{
|
||||
//Default Initialize data
|
||||
for (int i = 0; i < data.Length; i++)
|
||||
{
|
||||
data[i] = (byte)'S';
|
||||
}
|
||||
}
|
||||
virtual public void getResponseData(byte[] data, byte[] origPacketReceived, int dataSegOffset)
|
||||
{
|
||||
for(int i = 0; i < data.Length; i++)
|
||||
{
|
||||
data[i] = origPacketReceived[i+dataSegOffset];
|
||||
}
|
||||
}
|
||||
|
||||
virtual public bool continueVerification(int actualBytesReceived, byte[] sent, byte[] received)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
virtual public bool verifyReceivedMessage(byte[] rec)
|
||||
{
|
||||
return (rec.Length == packetSize + headerOffset + ipHeaderOffset);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\client\spark_api\spark_api.csproj" />
|
||||
<ProjectReference Include="..\..\client\spark_core\spark_core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Experimental.System.Messaging" Version="1.1.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Reference in new issue
Block a user