public static void SendTo(this UDPClient UDPClient, String UDPPacketString, IIPAddress RemoteIPAddress, IPPort IPPort, Encoding Encoding = null, SocketFlags SocketFlags = SocketFlags.None) { if (Encoding == null) Encoding = Encoding.UTF8; var UDPPacketData = Encoding.GetBytes(UDPPacketString); var RemoteIPEndPoint = new IPEndPoint(new IPAddress(RemoteIPAddress.GetBytes()), IPPort.ToInt32()); UDPClient.SendTo(UDPPacketData, RemoteIPEndPoint, SocketFlags); }
/// <summary> /// Initialize the TCP server using the given parameters. /// </summary> /// <param name="IIPAddress">The listening IP address(es)</param> /// <param name="Port">The listening port</param> /// <param name="ServiceBanner">Service banner.</param> /// <param name="ServerThreadName">The optional name of the TCP server thread.</param> /// <param name="ServerThreadPriority">The optional priority of the TCP server thread.</param> /// <param name="ServerThreadIsBackground">Whether the TCP server thread is a background thread or not.</param> /// <param name="ConnectionIdBuilder">An optional delegate to build a connection identification based on IP socket information.</param> /// <param name="ConnectionThreadsNameBuilder">An optional delegate to set the name of the TCP connection threads.</param> /// <param name="ConnectionThreadsPriorityBuilder">An optional delegate to set the priority of the TCP connection threads.</param> /// <param name="ConnectionThreadsAreBackground">Whether the TCP connection threads are background threads or not (default: yes).</param> /// <param name="ConnectionTimeout">The TCP client timeout for all incoming client connections in seconds (default: 30 sec).</param> /// <param name="MaxClientConnections">The maximum number of concurrent TCP client connections (default: 4096).</param> /// <param name="Autostart">Start the TCP server thread immediately (default: no).</param> public TCPServer(IIPAddress IIPAddress, IPPort Port, String ServiceBanner = __DefaultServiceBanner, String ServerThreadName = null, ThreadPriority ServerThreadPriority = ThreadPriority.AboveNormal, Boolean ServerThreadIsBackground = true, ConnectionIdBuilder ConnectionIdBuilder = null, ConnectionThreadsNameBuilder ConnectionThreadsNameBuilder = null, ConnectionThreadsPriorityBuilder ConnectionThreadsPriorityBuilder = null, Boolean ConnectionThreadsAreBackground = true, TimeSpan?ConnectionTimeout = null, UInt32 MaxClientConnections = __DefaultMaxClientConnections, Boolean Autostart = false) { #region TCP Socket this._IPAddress = IIPAddress; this._Port = Port; this._IPSocket = new IPSocket(_IPAddress, _Port); this._TCPListener = new TcpListener(new System.Net.IPAddress(_IPAddress.GetBytes()), _Port.ToInt32()); #endregion #region TCP Server this._ServiceBanner = (ServiceBanner.IsNotNullOrEmpty()) ? ServiceBanner : __DefaultServiceBanner; this.ServerThreadName = (ServerThreadName != null) ? ServerThreadName : __DefaultServerThreadName + this.IPSocket.ToString(); this.ServerThreadPriority = ServerThreadPriority; this.ServerThreadIsBackground = ServerThreadIsBackground; #endregion #region TCP Connections this._TCPConnections = new ConcurrentDictionary <IPSocket, TCPConnection>(); this.ConnectionIdBuilder = (ConnectionIdBuilder != null) ? ConnectionIdBuilder : (Sender, Timestamp, LocalSocket, RemoteIPSocket) => "TCP:" + RemoteIPSocket.IPAddress + ":" + RemoteIPSocket.Port; this.ConnectionThreadsNameBuilder = (ConnectionThreadsNameBuilder != null) ? ConnectionThreadsNameBuilder : (Sender, Timestamp, LocalSocket, RemoteIPSocket) => "TCP thread " + RemoteIPSocket.IPAddress + ":" + RemoteIPSocket.Port; this.ConnectionThreadsPriorityBuilder = (ConnectionThreadsPriorityBuilder != null) ? ConnectionThreadsPriorityBuilder : (Sender, Timestamp, LocalSocket, RemoteIPSocket) => ThreadPriority.AboveNormal; this.ConnectionThreadsAreBackground = ConnectionThreadsAreBackground; this._ConnectionTimeout = ConnectionTimeout.HasValue ? ConnectionTimeout.Value : TimeSpan.FromSeconds(30); this._MaxClientConnections = MaxClientConnections; #endregion #region TCP Listener Thread this.CancellationTokenSource = new CancellationTokenSource(); this.CancellationToken = CancellationTokenSource.Token; _ListenerThread = new Thread(() => { #if __MonoCS__ // Code for Mono C# compiler #else Thread.CurrentThread.Name = this.ServerThreadName; Thread.CurrentThread.Priority = this.ServerThreadPriority; Thread.CurrentThread.IsBackground = this.ServerThreadIsBackground; #endif #region SetSocketOptions // IOControlCode.* // fd.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, tcpKeepalive); // bytes.PutInteger(endian, tcpKeepalive, 0); // bytes.PutInteger(endian, tcpKeepaliveIdle, 4); // bytes.PutInteger(endian, tcpKeepaliveIntvl, 8); // fd.IOControl(IOControlCode.KeepAliveValues, (byte[])bytes, null); #endregion try { _IsRunning = true; while (!_StopRequested) { // Wait for a new/pending client connection while (!_StopRequested && !_TCPListener.Pending()) { Thread.Sleep(5); } // Break when a server stop was requested if (_StopRequested) { break; } // Processing the pending client connection within its own task var NewTCPClient = _TCPListener.AcceptTcpClient(); // var NewTCPConnection = _TCPListener.AcceptTcpClientAsync(). // ContinueWith(a => new TCPConnection(this, a.Result)); // // ConfigureAwait(false); // Store the new connection //_SocketConnections.AddOrUpdate(_TCPConnection.Value.RemoteSocket, // _TCPConnection.Value, // (RemoteEndPoint, TCPConnection) => TCPConnection); Task.Factory.StartNew(Tuple => { try { var _Tuple = Tuple as Tuple <TCPServer, TcpClient>; var NewTCPConnection = new ThreadLocal <TCPConnection>( () => new TCPConnection(_Tuple.Item1, _Tuple.Item2) ); #region Copy ExceptionOccured event handlers //foreach (var ExceptionOccuredHandler in MyEventStorage) // _TCPConnection.Value.OnExceptionOccured += ExceptionOccuredHandler; #endregion #region OnNewConnection // If this event closes the TCP connection the OnNotification event will never be fired! // Therefore you can use this event for filtering connection initiation requests. OnNewConnection?.Invoke(NewTCPConnection.Value.TCPServer, NewTCPConnection.Value.ServerTimestamp, NewTCPConnection.Value.RemoteSocket, NewTCPConnection.Value.ConnectionId, NewTCPConnection.Value); if (!NewTCPConnection.Value.IsClosed) { OnNotification?.Invoke(NewTCPConnection.Value); } #endregion } catch (Exception e) { while (e.InnerException != null) { e = e.InnerException; } OnExceptionOccured?.Invoke(this, DateTime.Now, e); Console.WriteLine(DateTime.Now + " " + e.Message + Environment.NewLine + e.StackTrace); } }, new Tuple <TCPServer, TcpClient>(this, NewTCPClient)); } #region Shutdown // Request all client connections to finish! foreach (var _SocketConnection in _TCPConnections) { _SocketConnection.Value.StopRequested = true; } // After stopping the TCPListener wait for // all client connections to finish! while (_TCPConnections.Count > 0) { Thread.Sleep(5); } #endregion } #region Exception handling catch (Exception Exception) { var OnExceptionLocal = OnExceptionOccured; if (OnExceptionLocal != null) { OnExceptionLocal(this, DateTime.Now, Exception); } } #endregion _IsRunning = false; }); #endregion if (Autostart) { Start(); } }
/// <summary> /// Create a new UDP receiver listening on the given IP address and port. /// </summary> /// <param name="IPAddress">The IP address to listen.</param> /// <param name="Port">The port to listen.</param> /// <param name="ServiceBanner">Service banner.</param> /// <param name="Mapper">A delegate to transform the incoming UDP packets into custom data structures.</param> /// <param name="ReceiverThreadName">The optional name of the UDP receiver thread.</param> /// <param name="ReceiverThreadPriority">The optional priority of the UDP receiver thread.</param> /// <param name="ReceiverThreadIsBackground">Whether the UDP receiver thread is a background thread or not.</param> /// <param name="PacketThreadsNameCreator">An optional delegate to set the name of the UDP packet threads.</param> /// <param name="PacketThreadsPriority">The optional priority of the UDP packet threads.</param> /// <param name="PacketThreadsAreBackground">Whether the UDP packet threads are background threads or not.</param> /// <param name="Autostart">Start the UDP receiver thread immediately.</param> public UDPReceiver(IIPAddress IPAddress, IPPort Port, String ServiceBanner = DefaultServiceBanner, MapperDelegate Mapper = null, MapReduceDelegate MapReduce = null, String ReceiverThreadName = "UDP receiver thread", ThreadPriority ReceiverThreadPriority = ThreadPriority.AboveNormal, Boolean ReceiverThreadIsBackground = true, Func <UDPPacket <TData>, String> PacketThreadsNameCreator = null, ThreadPriority PacketThreadsPriority = ThreadPriority.AboveNormal, Boolean PacketThreadsAreBackground = true, Boolean Autostart = false) { if (Mapper == null && MapReduce == null) { throw new ArgumentNullException("The mapper and mapreduce delegate can not be both null!"); } this._IPAddress = IPAddress; this._IsMulticast = IPAddress.IsMulticast; this._Port = Port; this._IPSocket = new IPSocket(_IPAddress, _Port); this.ServiceBanner = ServiceBanner; this.Mapper = Mapper; this.MapReduce = MapReduce; this._ReceiverThreadName = ReceiverThreadName; this._ReceiverThreadPriority = ReceiverThreadPriority; this.PacketThreadsNameCreator = (PacketThreadsNameCreator == null) ? UDPpacket => "UDP packet from " + UDPpacket.RemoteSocket.IPAddress + ":" + UDPpacket.RemoteSocket.Port : PacketThreadsNameCreator; this._PacketThreadsPriority = PacketThreadsPriority; this._PacketThreadsAreBackground = PacketThreadsAreBackground; var LocalIPEndPoint = new IPEndPoint(new System.Net.IPAddress(_IPAddress.GetBytes()), _Port.ToInt32()); this.LocalSocket = new IPSocket(LocalIPEndPoint); this.LocalDotNetSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); this.LocalDotNetSocket.Bind(LocalIPEndPoint); this.BufferSize = 65536; this.ReceiveTimeout = 5000; if (IsMulticast) { LocalDotNetSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(System.Net.IPAddress.Parse(_IPAddress.ToString()), System.Net.IPAddress.Any)); } this.CancellationTokenSource = new CancellationTokenSource(); this.CancellationToken = CancellationTokenSource.Token; if (Autostart) { Start(); } }
public static void SendTo(this UDPClient UDPClient, Byte[] UDPPacketData, IIPAddress RemoteIPAddress, IPPort IPPort, SocketFlags SocketFlags = SocketFlags.None) { var RemoteIPEndPoint = new IPEndPoint(new IPAddress(RemoteIPAddress.GetBytes()), IPPort.ToInt32()); UDPClient.SendTo(UDPPacketData, RemoteIPEndPoint, SocketFlags); }
/// <summary> /// The UDPMulticastSenderArrow sends the incoming message /// to the given IP multicast group. /// </summary> /// <param name="MulticastAddress">The multicast address to join.</param> /// <param name="IPPort">The outgoing IP port to use.</param> /// <param name="HopCount">The IPv6 hop-count or IPv4 time-to-live field of the outgoing IP multicast packets.</param> public UDPMulticastSenderArrow(String MulticastAddress, IPPort IPPort, Byte HopCount = 255) { this.MulticastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); this.IPEndPoint = new IPEndPoint(IPAddress.Parse(MulticastAddress), IPPort.ToInt32()); this.HopCount = HopCount; }