本文整理汇总了C#中Connection.SendObject方法的典型用法代码示例。如果您正苦于以下问题:C# Connection.SendObject方法的具体用法?C# Connection.SendObject怎么用?C# Connection.SendObject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Connection
的用法示例。
在下文中一共展示了Connection.SendObject方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: PushItemToPeer
/// <summary>
/// Introduces a new item into the swarm and sends a build command to the originating requester
/// </summary>
/// <param name="peerConnection">The peer which requested the DFS item</param>
/// <param name="itemToDistribute">The item to be distributed</param>
/// <param name="completedPacketType">The packet type to use once the item has been fully assembled</param>
public static void PushItemToPeer(Connection peerConnection, DistributedItem itemToDistribute, string completedPacketType)
{
try
{
if (peerConnection.ConnectionInfo.ConnectionType != ConnectionType.TCP)
throw new Exception("Only able to push DFS item when the request is made via TCP.");
if (itemToDistribute.ItemClosed)
throw new ArgumentException("Unable to push a closed item.");
ItemAssemblyConfig assemblyConfig;
lock (globalDFSLocker)
{
//First double check to see if it's already in the swarm
if (!ItemAlreadyInLocalCache(itemToDistribute))
swarmedItemsDict.Add(itemToDistribute.Data.CompleteDataCheckSum, itemToDistribute);
else
itemToDistribute = swarmedItemsDict[itemToDistribute.Data.CompleteDataCheckSum];
}
itemToDistribute.IncrementPushCount();
//We add the requester to the item swarm at this point
itemToDistribute.SwarmChunkAvailability.AddOrUpdateCachedPeerChunkFlags(peerConnection.ConnectionInfo, new ChunkFlags(0));
//There is a possibility when we create this assembly config that the peer has been removed again
//We handle this on the peer end
assemblyConfig = new ItemAssemblyConfig(itemToDistribute, completedPacketType);
//Send the config information to the client that wanted the file
peerConnection.SendObject("DFS_IncomingLocalItemBuild", assemblyConfig, nullCompressionSRO);
if (DFS.loggingEnabled) DFS._DFSLogger.Debug("Pushed DFS item " + itemToDistribute.Data.CompleteDataCheckSum + " to peer " + peerConnection + ".");
}
catch (CommsException)
{
//LogTools.LogException(ex, "CommsError_AddItemToSwarm");
}
catch (Exception ex)
{
LogTools.LogException(ex, "Error_AddItemToSwarm");
}
//try { GC.Collect(); }
//catch (Exception) { }
}
示例2: IncomingChunkInterestRequest
/// <summary>
/// UDP - Received when a peer request a chunk
/// </summary>
/// <param name="packetHeader"></param>
/// <param name="connection"></param>
/// <param name="incomingRequest"></param>
private static void IncomingChunkInterestRequest(PacketHeader packetHeader, Connection connection, ChunkAvailabilityRequest incomingRequest)
{
try
{
//A peer has requested a specific chunk of data, we will only provide it if we are not already providing it to someone else
DateTime startTime = DateTime.Now;
//Console.WriteLine("... ({0}) received request for chunk {1} from {2}.", DateTime.Now.ToString("HH:mm:ss.fff"), incomingRequest.ChunkIndex, sourceConnectionId);
if (DFS.loggingEnabled) DFS._DFSLogger.Trace("IncomingChunkInterestRequest from " + connection + " for " + incomingRequest.ItemCheckSum + ", chunkIndex " + incomingRequest.ChunkIndex + ".");
DistributedItem selectedItem = null;
lock (globalDFSLocker)
if (swarmedItemsDict.ContainsKey(incomingRequest.ItemCheckSum))
selectedItem = swarmedItemsDict[incomingRequest.ItemCheckSum];
if (selectedItem == null || (selectedItem != null && selectedItem.ItemClosed))
{
//First reply and say the peer can't have the requested data. This prevents a request timing out
connection.SendObject("DFS_ChunkAvailabilityInterestReplyInfo", new ChunkAvailabilityReply(NetworkComms.NetworkIdentifier, incomingRequest.ItemCheckSum, incomingRequest.ChunkIndex, ChunkReplyState.ItemOrChunkNotAvailable), nullCompressionSRO);
//Inform peer that we don't actually have the requested item
UDPConnection.SendObject("DFS_ItemRemovalUpdate", new ItemRemovalUpdate(NetworkComms.NetworkIdentifier, incomingRequest.ItemCheckSum, false), (IPEndPoint)connection.ConnectionInfo.RemoteEndPoint, nullCompressionSRO);
if (DFS.loggingEnabled) DFS._DFSLogger.Trace(" ... item not available locally, sent DFS_ItemRemovalUpdate.");
}
else
{
//A little request validation
if (incomingRequest.ChunkIndex > selectedItem.Data.TotalNumChunks)
throw new InvalidDataException("The incoming request wanted chunk #" + incomingRequest.ChunkIndex +
" when the selected item only has " + selectedItem.Data.TotalNumChunks + "chunks.");
if (!selectedItem.ChunkAvailableLocally(incomingRequest.ChunkIndex))
{
//First reply and say the peer can't have the requested data. This prevents a request timing out
connection.SendObject("DFS_ChunkAvailabilityInterestReplyInfo", new ChunkAvailabilityReply(NetworkComms.NetworkIdentifier, incomingRequest.ItemCheckSum, incomingRequest.ChunkIndex, ChunkReplyState.ItemOrChunkNotAvailable), nullCompressionSRO);
//If the peer thinks we have a chunk we don't we send them an update so that they are corrected
UDPConnection.SendObject("DFS_PeerChunkAvailabilityUpdate", new PeerChunkAvailabilityUpdate(NetworkComms.NetworkIdentifier, incomingRequest.ItemCheckSum, selectedItem.SwarmChunkAvailability.PeerChunkAvailability(NetworkComms.NetworkIdentifier)), (IPEndPoint)connection.ConnectionInfo.RemoteEndPoint, nullCompressionSRO);
if (DFS.loggingEnabled) DFS._DFSLogger.Trace(" ... requested chunk not available, sent DFS_PeerChunkAvailabilityUpdate.");
}
else
{
//If we are a super peer we always have to respond to the request
if (HostInfo.IP.AverageNetworkLoadOutgoing(10) > DFS.PeerBusyNetworkLoadThreshold && !selectedItem.SwarmChunkAvailability.PeerIsSuperPeer(NetworkComms.NetworkIdentifier))
{
//We can return a busy reply if we are currently experiencing high demand
connection.SendObject("DFS_ChunkAvailabilityInterestReplyInfo", new ChunkAvailabilityReply(NetworkComms.NetworkIdentifier, incomingRequest.ItemCheckSum, incomingRequest.ChunkIndex, ChunkReplyState.PeerBusy), nullCompressionSRO);
if (DFS.loggingEnabled) DFS._DFSLogger.Trace(" ... peer busy, sent busy response.");
}
else
{
StreamTools.StreamSendWrapper chunkData = selectedItem.GetChunkDataStream(incomingRequest.ChunkIndex);
if (DFS.loggingEnabled) DFS._DFSLogger.Trace("Pushing chunkData to " + connection + " for item:" + incomingRequest.ItemCheckSum + ", chunkIndex:" + incomingRequest.ChunkIndex + ".");
//We identify the data using the itemchecksum, the requested chunk index, and to unique identify this request from possible duplicates
//we append the requesting peer request index.
string packetIdentifier = selectedItem.Data.CompleteDataCheckSum + "-" + incomingRequest.ChunkIndex + "-" + incomingRequest.RequestNumIndex;
//This is received via UDP but we want to reply using TCP to ensure delivery of the data
var clientTCPConnection = TCPConnection.GetConnection(new ConnectionInfo(connection.ConnectionInfo.RemoteEndPoint));
//Send using a custom packet so that we can add the packet identifier
using (Packet sendPacket = new Packet("DFS_ChunkAvailabilityInterestReplyData", chunkData, nullCompressionSRO))
{
sendPacket.PacketHeader.SetOption(PacketHeaderStringItems.PacketIdentifier, packetIdentifier);
clientTCPConnection.SendPacket<StreamTools.StreamSendWrapper>(sendPacket);
}
if (DFS.loggingEnabled) DFS._DFSLogger.Trace("Pushing chunkInfo to " + connection + " for item:" + incomingRequest.ItemCheckSum + ", chunkIndex:" + incomingRequest.ChunkIndex + ".");
clientTCPConnection.SendObject("DFS_ChunkAvailabilityInterestReplyInfo", new ChunkAvailabilityReply(NetworkComms.NetworkIdentifier, incomingRequest.ItemCheckSum, incomingRequest.ChunkIndex, packetIdentifier), nullCompressionSRO);
lock (TotalNumReturnedChunkRequestsLocker) TotalNumReturnedChunkRequests++;
if (DFS.loggingEnabled) DFS._DFSLogger.Trace(" ... IncomingChunkInterestRequest completed with data in " + (DateTime.Now - startTime).TotalSeconds.ToString("0.0") + " seconds.");
}
}
}
}
catch (ObjectDisposedException)
{
//This happens if we dispose the DFS item during this method execution
if (loggingEnabled) Logger.Warn("Prevented ObjectDisposedException in IncomingChunkInterestRequest");
}
catch (ConnectionSetupException)
{
//Ignore, the peer is offline
}
catch (CommunicationException)
{
//.........这里部分代码省略.........
示例3: IncomingRemoteItemLinkRequest
/// <summary>
/// TCP - A remote peer is trying to link DFS items
/// </summary>
/// <param name="packetHeader"></param>
/// <param name="connection"></param>
/// <param name="linkRequestData"></param>
private static void IncomingRemoteItemLinkRequest(PacketHeader packetHeader, Connection connection, DFSLinkRequest linkRequestData)
{
try
{
var localItemKeys = AllLocalDFSItemsWithBuildTime();
//We only check for potential links if the remote end has provided us with some items to link
if (linkRequestData.AvailableItems.Count > 0)
{
//Get the item matches using linq. Could also use localItemKeys.Intersect<long>(linkRequestData.AvailableItemCheckSums);
DistributedItem[] itemsToLink = null;
lock (globalDFSLocker)
itemsToLink= (from current in localItemKeys.Keys
join remote in linkRequestData.AvailableItems.Keys on current equals remote
where swarmedItemsDict.ContainsKey(current)
select swarmedItemsDict[current]).ToArray();
for (int i = 0; i < itemsToLink.Length; i++)
itemsToLink[i].SwarmChunkAvailability.AddOrUpdateCachedPeerChunkFlags(connection.ConnectionInfo, new ChunkFlags(itemsToLink[i].Data.TotalNumChunks), true);
}
//If this link request is from the original requester then we reply with our own items list
if (!linkRequestData.LinkRequestReply)
{
//If a specific return packet type has been requested we use that
if (packetHeader.RequestedReturnPacketType != null)
connection.SendObject(packetHeader.RequestedReturnPacketType, new DFSLinkRequest(localItemKeys, true), nullCompressionSRO);
else
connection.SendObject("DFS_ItemLinkRequest", new DFSLinkRequest(localItemKeys, true), nullCompressionSRO);
}
}
catch (CommsException e)
{
LogTools.LogException(e, "CommsError_IncomingRemoteItemLinkRequest");
}
catch (Exception e)
{
LogTools.LogException(e, "Error_IncomingRemoteItemLinkRequest");
}
}
示例4: PeerDiscoveryHandler
/// <summary>
/// Handle the incoming peer discovery packet
/// </summary>
/// <param name="header"></param>
/// <param name="connection"></param>
/// <param name="data"></param>
private static void PeerDiscoveryHandler(PacketHeader header, Connection connection, byte[] data)
{
DiscoveryMethod discoveryMethod = DiscoveryMethod.UDPBroadcast;
#if !NETFX_CORE && !WINDOWS_PHONE
if (connection.ConnectionInfo.ConnectionType == ConnectionType.TCP)
discoveryMethod = DiscoveryMethod.TCPPortScan;
#endif
#if NET35 || NET4
else if (connection.ConnectionInfo.ConnectionType == ConnectionType.Bluetooth)
discoveryMethod = DiscoveryMethod.BluetoothSDP;
#endif
//Ignore discovery packets that came from this peer
if (!Connection.ExistingLocalListenEndPoints(connection.ConnectionInfo.ConnectionType).Contains(connection.ConnectionInfo.RemoteEndPoint))
{
//If the only thing that was sent was an empty byte array this is a peer discovery request.
if (data.Length == 0 && IsDiscoverable(discoveryMethod))
{
//Send back our listener info
byte[] responseData = SerializeLocalListenerList();
connection.SendObject(discoveryPacketType, responseData);
}
else if (data.Length > 0)
{
//This is a peer discovery reply, we may need to add this to the tracking dictionary
ShortGuid peerIdentifier;
//If this is the case then we have found listeners on a peer and we need to add them to our known peers
List<PeerListenerEndPoint> remoteListeners = DeserializeRemoteListenerList(data, out peerIdentifier);
Dictionary<ConnectionType, List<EndPoint>> discoveredPeerListeners = new Dictionary<ConnectionType, List<EndPoint>>();
foreach (PeerListenerEndPoint peer in remoteListeners)
{
if (discoveredPeerListeners.ContainsKey(peer.ConnectionType))
discoveredPeerListeners[peer.ConnectionType].Add(peer.EndPoint);
else
discoveredPeerListeners.Add(peer.ConnectionType, new List<EndPoint>() { peer.EndPoint });
}
bool newlyDiscoveredPeerEndPoint = false;
lock (_syncRoot)
{
if (!_discoveredPeers.ContainsKey(peerIdentifier))
_discoveredPeers.Add(peerIdentifier, new Dictionary<ConnectionType, Dictionary<EndPoint, DateTime>>());
//If no remote listeners were returned we can only used the remoteEndPoint used to send this reply
if (remoteListeners.Count == 0)
{
if (!_discoveredPeers[peerIdentifier].ContainsKey(connection.ConnectionInfo.ConnectionType))
_discoveredPeers[peerIdentifier].Add(connection.ConnectionInfo.ConnectionType, new Dictionary<EndPoint, DateTime>());
if (!_discoveredPeers[peerIdentifier][connection.ConnectionInfo.ConnectionType].ContainsKey(connection.ConnectionInfo.RemoteEndPoint))
{
newlyDiscoveredPeerEndPoint = true;
_discoveredPeers[peerIdentifier][connection.ConnectionInfo.ConnectionType].Add(connection.ConnectionInfo.RemoteEndPoint, DateTime.Now);
}
}
else
{
foreach (PeerListenerEndPoint peerEndPoint in remoteListeners)
{
if (!_discoveredPeers[peerIdentifier].ContainsKey(peerEndPoint.ConnectionType))
{
newlyDiscoveredPeerEndPoint = true;
_discoveredPeers[peerIdentifier].Add(peerEndPoint.ConnectionType, new Dictionary<EndPoint, DateTime>() { { peerEndPoint.EndPoint, DateTime.Now } });
}
else if (!_discoveredPeers[peerIdentifier][peerEndPoint.ConnectionType].ContainsKey(peerEndPoint.EndPoint))
{
newlyDiscoveredPeerEndPoint = true;
_discoveredPeers[peerIdentifier][peerEndPoint.ConnectionType].Add(peerEndPoint.EndPoint, DateTime.Now);
}
}
}
}
//Trigger the discovery event if it has been set AND this is the first time a new peer end point was discovered
//If a peer is discoverable on multiple adaptors which we have access too we may receive numerous (duplicate)
//discovery reports. We are only interested in triggering on the first one, not subsequent identical copies.
//This ensures the synchronous and asynchronous methods execute in a similar fashion
if (OnPeerDiscovered != null && newlyDiscoveredPeerEndPoint)
OnPeerDiscovered(peerIdentifier, discoveredPeerListeners);
}
}
}