using System;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Collections.Generic;
namespace grof.protocols.membership{
/// <summary>
/// The <code>TcpSender</code> class is
/// responsible for sending a
/// <code>Message</code> object to all
/// group members of group via TCP protocol.
/// </summary>
class TcpSender
{
/// <summary>
/// The name of the group member.
/// </summary>
private string memberName;
/// <summary>
/// Creates objects of class
/// <code>TcpSender</code>.
/// </summary>
///
/// <returns></returns>
public TcpSender( string memberName )
{
this.memberName = memberName;
Debug.WriteLine( "[TcpSender#constructor] TCP sender created." );
}
/// <summary>
/// Sends a <code>Message</code> object to
/// all group members of a group
/// </summary>
///
/// <param name="msg">The Message object</param>.
///
/// <param name="gmInfos">The collection which contains all
/// group members of a group as
/// <code>GroupMemberInfo</code>objects.</param>
public void Send( Message msg, ICollection<GroupMemberInfo> gmInfos )
{
// iterating through all group members
foreach ( GroupMemberInfo gmInfo in gmInfos )
{
Socket clientSocket = null;
try
{
Debug.WriteLine( "[TcpSender#Send] " + this.memberName + ": Sending message to member " +
gmInfo.ToString() );
clientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
clientSocket.Connect(new IPEndPoint( IPAddress.Parse( gmInfo.GetHostAddress() ),
gmInfo.GetPortNumber() ) );
// Sending the message to the group member
clientSocket.Send( msg.ToBytes() );
} catch( SocketException se )
{
Debug.WriteLine( "[TcpSender#Send] " + this.memberName + ": Network error occurred during sending: "
+ se.ToString() );
} finally
{
if ( clientSocket != null )
{
clientSocket.Close();
}
Debug.WriteLine( "[TcpSender#Send] " + this.memberName + ": Socket closed." );
}
}
}
}
}
|