public virtual void SetSocketConfig(SocketConfig socketConfig) { lock (this) { this.socketConfig = socketConfig != null ? socketConfig : SocketConfig.Default; } }
internal MemoryManager(SocketConfig config) { _configuration = config; _pooledHeapMemory = new ConcurrentCircularQueue <HeapMemory>(_configuration.HeapMemoryPoolSize); _pooledPointerArrays = new ConcurrentCircularQueue <HeapPointers>(_configuration.HeapPointersPoolSize); _pooledMemoryWrappers = new ConcurrentCircularQueue <MemoryWrapper>(_configuration.MemoryWrapperPoolSize); }
/// <summary> /// Registers objects to the <see cref="container"/> /// </summary> public static void RegisterTypes() { container = new UnityContainer(); container.RegisterType <IBot, Bot>(new PerThreadLifetimeManager()); container.RegisterSingleton <IConnection, Connection>(); container.RegisterType <ILogger, Logger.Logger>(new PerThreadLifetimeManager()); // DI for discord container.RegisterFactory <DiscordSocketConfig>(i => SocketConfig.GetDefault(), new SingletonLifetimeManager()); container.RegisterFactory <CommandService>(i => CommandConfig.GetDefault(), new SingletonLifetimeManager()); container.RegisterSingleton <DiscordShardedClient>(new InjectionConstructor(typeof(DiscordSocketConfig))); container.RegisterSingleton <IClientLogHandler, ClientLogHandler>(); container.RegisterSingleton <IMiscEventHandler, MiscEventHandler>(); container.RegisterSingleton <IPrefixService, PrefixService>(); container.RegisterSingleton <IBotListUpdater, BotListUpdater>(); container.RegisterSingleton <DiscordBotListsUpdateTimer>(); container.RegisterType <ICommandErrorHandler, CommandErrorHandler>(new PerThreadLifetimeManager()); container.RegisterType <ICommandInputErrorHandler, CommandInputErrorHandler>(new PerThreadLifetimeManager()); container.RegisterType <ICommandHandler, CommandHandler>(new PerThreadLifetimeManager()); container.RegisterType <ISpamFilter, SpamFilter>(new PerThreadLifetimeManager()); // DI for Entity framework container.RegisterType <BotContext>(new PerResolveLifetimeManager()); container.RegisterType <IUnitOfWork, UnitOfWork>(new PerResolveLifetimeManager()); container.RegisterType <IRequestUnitOfWork, RequestUnitOfWork>(new PerResolveLifetimeManager()); container.RegisterType <IServerUnitOfWork, ServerUnitOfWork>(new PerResolveLifetimeManager()); container.RegisterType <IServerRepository, ServerRepository>(new PerResolveLifetimeManager()); container.RegisterType <IUserRepository, UserRepository>(new PerResolveLifetimeManager()); container.RegisterType <IRequestRepository, RequestRepository>(new PerResolveLifetimeManager()); }
private Socket GetRawSocket(SocketConfig socketConfig) { IPEndPoint ep = (IPEndPoint)socketConfig.EndPoint; // Setting Socket.DontFragment and .Ttl is not supported on Unix, so socketConfig.Options is ignored. AddressFamily addrFamily = ep.Address.AddressFamily; Socket socket = new Socket(addrFamily, SocketType.Raw, socketConfig.ProtocolType); socket.ReceiveTimeout = socketConfig.Timeout; socket.SendTimeout = socketConfig.Timeout; if (socketConfig.Options != null && socketConfig.Options.Ttl > 0) { socket.Ttl = (short)socketConfig.Options.Ttl; } if (socketConfig.Options != null && addrFamily == AddressFamily.InterNetwork) { socket.DontFragment = socketConfig.Options.DontFragment; } #pragma warning disable 618 // Disable warning about obsolete property. We could use GetAddressBytes but that allocates. // IPv4 multicast address starts with 1110 bits so mask rest and test if we get correct value e.g. 0xe0. if (!ep.Address.IsIPv6Multicast && !(addrFamily == AddressFamily.InterNetwork && (ep.Address.Address & 0xf0) == 0xe0)) { // If it is not multicast, use Connect to scope responses only to the target address. socket.Connect(socketConfig.EndPoint); } #pragma warning restore 618 return(socket); }
public static string GetResponseFailed(string transactionID, string message, SocketConfig config) { StringBuilder sb = new StringBuilder(); //if (Program.ConfigMgt.Config.IncludeResponseHeader) //{ // sb.Append(ResponseHeader); //} sb.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); sb.AppendLine("<XMLResponseMessage SchemaVersion=\"1.0\">"); sb.AppendLine(" <XISVersion>3.0.</XISVersion>"); sb.AppendLine(" <Name>EVENT_COMPLETE</Name>"); sb.AppendLine(" <TransactionID>" + transactionID + "</TransactionID>"); sb.AppendLine(" <Status>"); sb.AppendLine(" <Code>GENERAL_FAILURE</Code>"); sb.AppendLine(" <FailureCode>ERROR_PARSING_REQUEST</FailureCode>"); sb.AppendLine(" <Message>"+ message + "</Message>"); sb.AppendLine(" </Status>"); sb.AppendLine(" <DeviceResponse>"); sb.AppendLine(" <Device>"+ config.SourceDeviceName + "</Device>"); sb.AppendLine(" <Status>"); sb.AppendLine(" <Code>CANCELED_TRANSACTION</Code>"); sb.AppendLine(" <Message>"+ message + "</Message>"); sb.AppendLine(" </Status>"); sb.AppendLine(" </DeviceResponse>"); sb.AppendLine(" <XIM XIMSchemaVersion=\"2.0\">"); sb.AppendLine(" </XIM>"); sb.Append("</XMLResponseMessage>"); return(sb.ToString()); }
private void buttonInboundSend_Click(object sender, EventArgs e) { string sendData = this.textBoxClientSend.Text; //SocketResult result = SocketHelper.SendData("127.0.0.1", (int)this.numericUpDownClientPort.Value, sendData); SocketConfig config = new SocketConfig(); config.Port = (int)this.numericUpDownClientPort.Value; config.IPAddress = "127.0.0.1"; config.SendEndSign = "</XMLRequestMessage>"; config.ReceiveEndSign = "</XMLResponseMessage>"; config.IncludeHeader = false; SocketResult result = SocketHelper.SendData(config, sendData); if (result.Type == SocketResultType.Success) { this.textBoxClientReceive.Text = result.ReceivedString; } else { //MessageBox.Show(result.ExceptionInfor, result.Type.ToString()); } Application.DoEvents(); }
private SocketConfig GetSocketConfig(IPAddress address, byte[] buffer, int timeout, PingOptions options) { SocketConfig config = new SocketConfig(); config.EndPoint = new IPEndPoint(address, 0); config.Timeout = timeout; config.Options = options; config.IsIpv4 = address.AddressFamily == AddressFamily.InterNetwork; config.ProtocolType = config.IsIpv4 ? ProtocolType.Icmp : ProtocolType.IcmpV6; // Use a random value as the identifier. This doesn't need to be perfectly random // or very unpredictable, rather just good enough to avoid unexpected conflicts. Random rand = t_idGenerator ?? (t_idGenerator = new Random()); config.Identifier = (ushort)rand.Next((int)ushort.MaxValue + 1); IcmpHeader header = new IcmpHeader() { Type = config.IsIpv4 ? (byte)IcmpV4MessageType.EchoRequest : (byte)IcmpV6MessageType.EchoRequest, Code = 0, HeaderChecksum = 0, Identifier = config.Identifier, SequenceNumber = 0, }; config.SendBuffer = CreateSendMessageBuffer(header, buffer); return(config); }
private void buttonServerStart_Click(object sender, EventArgs e) { //_server = SocketEntity.Create((int)this.numericUpDownServerPort.Value); SocketConfig config = new SocketConfig(); config.Port = (int)this.numericUpDownServerPort.Value; config.ReceiveEndSign = "</XMLRequestMessage>"; config.SendEndSign = "</XMLResponseMessage>"; _server = SocketEntity.Create(config); if (_server == null) { return; } _server.OnRequest += new RequestEventHandler(_server_OnRequest); if (_server == null) { MessageBox.Show(SocketLogMgt.LastErrorInfor); } else if (_server.Start()) { this.numericUpDownServerPort.Enabled = false; } else { MessageBox.Show(SocketLogMgt.LastErrorInfor); } }
public override SocketTasks StartClient() { SocketConfig config = GetConfig(false, NetworkingManager.Singleton.NetworkConfig); socket = new RuffleSocket(config); isConnector = true; if (!socket.Start()) { return(SocketTask.Fault.AsTasks()); } serverConnection = socket.Connect(new IPEndPoint(IPAddress.Parse(ConnectAddress), Port)); if (serverConnection == null) { return(SocketTask.Fault.AsTasks()); } else { connectTask = SocketTask.Working; return(connectTask.AsTasks()); } }
internal Connection(SocketConfig config) { if (config.EnableHeartbeats) { HeartbeatChannel = new UnreliableSequencedChannel(0, this); } }
public static void ConfigGetNewTest() { var actual = SocketConfig.GetNew(); Assert.NotNull(actual); Assert.IsType <DiscordSocketConfig>(actual); }
/// <summary> /// Gets the stored config file /// </summary> /// <returns></returns> public static SocketConfig GetConfig() { string jsonString = File.ReadAllText(CONFIG_FOLDER + "/" + CONFIG_FILENAME); SocketConfig config = JsonConvert.DeserializeObject <SocketConfig>(jsonString); return(config); }
internal UnreliableRawChannel(byte channelId, Connection connection, SocketConfig config, MemoryManager memoryManager) { this.channelId = channelId; this.connection = connection; this.config = config; this.memoryManager = memoryManager; }
public override void Start(SocketConfig socketConfig) { if (socketConfig == null) { throw new ArgumentNullException(nameof(socketConfig)); } _connections = new ConcurrentDictionary <EndPoint, SocketService>(); if (socketConfig.OpenKeepAlive) { _udpKeepAlive = new UdpKeepAlive(); _udpKeepAlive.Start(socketConfig.KeepAliveInterval, socketConfig.ReconnectMaxCount); } if (socketConfig.OpenFragmentResend) { _fragmentTimer = new FragmentsTimer(); _fragmentTimer.Start(socketConfig.FragmentInterval); } var endPoint = new IPEndPoint(IPAddress.Parse(socketConfig.IP), socketConfig.Port); _readSocket = CreateSocket(endPoint.AddressFamily, endPoint); var socketService = PoolAllocator <SocketService> .GetObject(); socketService.Connection.LocalAddress = endPoint; BeginRead(socketService); }
public void Assign(byte channelId, Connection connection, SocketConfig config, MemoryManager memoryManager) { this.channelId = channelId; this.connection = connection; this.config = config; this.memoryManager = memoryManager; }
private async Task <PingReply> SendIcmpEchoRequestOverRawSocketAsync(IPAddress address, byte[] buffer, int timeout, PingOptions?options) { SocketConfig socketConfig = GetSocketConfig(address, buffer, timeout, options); using (Socket socket = GetRawSocket(socketConfig)) { int ipHeaderLength = socketConfig.IsIpv4 ? MinIpHeaderLengthInBytes : 0; CancellationTokenSource timeoutTokenSource = new CancellationTokenSource(timeout); try { await socket.SendToAsync( new ArraySegment <byte>(socketConfig.SendBuffer), SocketFlags.None, socketConfig.EndPoint, timeoutTokenSource.Token) .ConfigureAwait(false); byte[] receiveBuffer = new byte[MaxIpHeaderLengthInBytes + IcmpHeaderLengthInBytes + buffer.Length]; Stopwatch sw = Stopwatch.StartNew(); // Read from the socket in a loop. We may receive messages that are not echo replies, or that are not in response // to the echo request we just sent. We need to filter such messages out, and continue reading until our timeout. // For example, when pinging the local host, we need to filter out our own echo requests that the socket reads. while (!timeoutTokenSource.IsCancellationRequested) { SocketReceiveFromResult receiveResult = await socket.ReceiveFromAsync( new ArraySegment <byte>(receiveBuffer), SocketFlags.None, socketConfig.EndPoint, timeoutTokenSource.Token) .ConfigureAwait(false); int bytesReceived = receiveResult.ReceivedBytes; if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes) { continue; // Not enough bytes to reconstruct IP header + ICMP header. } if (TryGetPingReply(socketConfig, receiveBuffer, bytesReceived, sw, ref ipHeaderLength, out PingReply? reply)) { return(reply); } } } catch (SocketException ex) when(ex.SocketErrorCode == SocketError.TimedOut) { } catch (OperationCanceledException) { } finally { timeoutTokenSource.Dispose(); } // We have exceeded our timeout duration, and no reply has been received. return(CreateTimedOutPingReply()); } }
internal ReliableChannel(byte channelId, Connection connection, SocketConfig config) { this.channelId = channelId; this.connection = connection; this.config = config; _sendSequencer = new HeapableSlidingWindow <PendingOutgoingPacket>(config.ReliabilityWindowSize, true, sizeof(ushort)); }
public void ConfigDefaultTests() { const LogSeverity expected = LogSeverity.Verbose; var actual = SocketConfig.GetDefault().LogLevel; Assert.Equal(expected, actual); }
// Used by Test project internal static Connection Stub(SocketConfig config) { return(new Connection(0, ConnectionState.Connected, new IPEndPoint(IPAddress.Any, 0), new RuffleSocket(config)) { IsStub = true, MTU = config.MinimumMTU }); }
public override void StartServer() { SocketConfig config = GetConfig(); config.DualListenPort = (ushort)ServerListenPort; socket = new RuffleSocket(config); }
private void FormXIS_Load(object sender, EventArgs e) { SocketConfig config = new SocketConfig(); this.numericUpDownClientPort.Value = this.numericUpDownServerPort.Value = config.Port; SocketLogMgt.OnError += new EventHandler(SocketEntity_OnError); }
// Used by Test project internal static Connection Stub(SocketConfig config, MemoryManager manager) { return(new Connection(config, manager) { IsStub = true, MTU = config.MinimumMTU }); }
internal UnreliableChannel(byte channelId, Connection connection, SocketConfig config) { this.channelId = channelId; this.connection = connection; this.config = config; _incomingAckedPackets = new SlidingWindow <bool>(config.ReliabilityWindowSize, true, sizeof(ushort)); }
internal UnreliableSequencedChannel(byte channelId, Connection connection, SocketConfig config, MemoryManager memoryManager) { this.channelId = channelId; this.connection = connection; this.memoryManager = memoryManager; this.config = config; _incomingAckedPackets = new SlidingWindow <bool>(config.ReliabilityWindowSize); }
public void Start(SocketConfig serverConfig) { if (serverConfig == null) { throw new ArgumentNullException(nameof(serverConfig)); } _messageQueue.Start(); Socket.Start(serverConfig); }
public static void RegisterTypes() { _container = new UnityContainer(); _container.RegisterSingleton <IDataStorage, JsonStorage>(); _container.RegisterSingleton <ILogger, Logger>(); _container.RegisterType <DiscordSocketConfig>(new InjectionFactory(i => SocketConfig.GetDefault())); _container.RegisterSingleton <DiscordSocketClient>(new InjectionConstructor(typeof(DiscordSocketConfig))); _container.RegisterSingleton <Discord.Connection>(); }
public static SocketConfig GetSocketConfig(HttpParams @params) { return(SocketConfig.Custom().SetSoTimeout(@params.GetIntParameter(CoreConnectionPNames .SoTimeout, 0)).SetSoReuseAddress(@params.GetBooleanParameter(CoreConnectionPNames .SoReuseaddr, false)).SetSoKeepAlive(@params.GetBooleanParameter(CoreConnectionPNames .SoKeepalive, false)).SetSoLinger(@params.GetIntParameter(CoreConnectionPNames.SoLinger , -1)).SetTcpNoDelay(@params.GetBooleanParameter(CoreConnectionPNames.TcpNodelay , true)).Build()); }
/// <summary> /// Method to handle the first message from the Discord websocket /// </summary> /// <param name="helloResume">Gateway payload sent from the websocket</param> private async Task OnHelloMessageAsync(GatewayHello helloResume) { this._socketClient.StartHeartbeatTimer(helloResume.HeartbeatInterval); GatewayIdentify gatewayIdentify = new GatewayIdentify(); _socketConfig = JsonStorage.GetConfig(); gatewayIdentify.Token = _socketConfig.Token; await this._socketClient.SendAsync(OpCodes.Identity, gatewayIdentify); }
private MasterServer SetService(SocketConfig socketConfig) { var masterServer = new MasterServer(socketConfig.ServiceID, RawMessageManager, ModuleManager, CacheManager, ControllerComponentManager); _services.TryAdd(socketConfig, masterServer); ServiceManager.AddService(socketConfig.ServiceID, masterServer); masterServer.InitializeModules(); return(masterServer); }
internal ReliableChannel(byte channelId, Connection connection, SocketConfig config, MemoryManager memoryManager) { this.channelId = channelId; this.connection = connection; this.config = config; this.memoryManager = memoryManager; _sendSequencer = new HeapableFixedDictionary <PendingOutgoingPacket>(config.ReliabilityWindowSize, memoryManager); _lastAckTimes = new SlidingWindow <NetTime>(config.ReliableAckFlowWindowSize); }
public Wiznet5100(SPI.SPI_module spiModule, Cpu.Pin chipSelect, Cpu.Pin interrupt) { // initialize our write/read commands with their respective first bytes m_writeCommand[0] = 0xF0; // 0xF0 = write data byte m_readCommand[0] = 0x0F; // 0x0F = read data byte m_readCommand[3] = 0x00; // 0x00 = dummy filler data (to be transmitted while reading byte in ReadRegister) // setup our SPI connection parameters // TODO: we are using default assumptions here; validate hold and setup times and clock rates //m_spi = new SPI(new SPI.Configuration(chipSelect, false, 1, 1, false, true, 100, spiModule)); // start at 100KHz //m_spi = new SPI(new SPI.Configuration(Pins.GPIO_PIN_D10, false, 1, 1, false, true, 10000, SPI.SPI_module.SPI1)); // then go to 10MHz //m_spi = new SPI(new SPI.Configuration(chipSelect, false, 1, 1, false, true, 15000, spiModule)); // then go to 15MHz m_spi = new SPI(new SPI.Configuration(chipSelect, false, 0, 0, false, true, 15000, spiModule)); // then get rid of setup/release times //m_spi = new SPI(new SPI.Configuration(Pins.GPIO_PIN_D10, false, 0, 0, false, true, 100, SPI.SPI_module.SPI1)); // as a failsafe, get rid of 1ms setup and 1ms release times and 100KHz // set up our socket config data... for (int i = 0; i < 4; i++) { m_SocketConfig[i] = new SocketConfig(); m_SocketConfig[i].AnyInterrupt = new AutoResetEvent(false); m_SocketConfig[i].ConnectedInterrupt = new AutoResetEvent(false); m_SocketConfig[i].DisconnectedInterrupt = new AutoResetEvent(false); m_SocketConfig[i].DataReceivedInterrupt = new AutoResetEvent(false); m_SocketConfig[i].TimeoutInterrupt = new AutoResetEvent(false); m_SocketConfig[i].DataWrittenInterrupt = new AutoResetEvent(false); m_SocketConfig[i].TransmitBufferLock = new object(); m_SocketConfig[i].ReceiveBufferLock = new object(); } // if an interrupt pin was specified, connect to it now... if (interrupt != Cpu.Pin.GPIO_NONE) { m_interruptPort = new InterruptPort(interrupt, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeLow); m_interruptPort.OnInterrupt += new NativeEventHandler(m_interruptPort_OnInterrupt); } // get our Wiznet network interface reference NetworkInterface networkInterface = NetworkInterface.GetAllNetworkInterfaces()[0]; // initialize our Wiznet chip using the settings from our NetworkInterface Init(networkInterface.PhysicalAddress, IPAddress.Parse(networkInterface.IPAddress), IPAddress.Parse(networkInterface.SubnetMask), IPAddress.Parse(networkInterface.GatewayAddress)); // configure out network interface with this WIZnet chip. ((Microsoft.SPOT.Net.NetworkInformation.W5100NetworkInterface)Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0]).WiznetChip = this; }
private void OnConfig(object sender, RoutedEventArgs e) { Config.LoadFromFile(); Window frm2 = new SocketConfig(this); frm2.Show(); }
public SocketWindow(out bool to_close) { to_close = false; InitializeComponent(); while (Config == null) { while (Config == null) { SocketConfig socketConfig = new SocketConfig(this); bool? userClickedOK = socketConfig.ShowDialog(); if (userClickedOK == false) { to_close = true; return; } else if (Config == null) { System.Windows.MessageBox.Show("Invalid configuration. Please, change it."); } } } if (!to_close) { // RunCommunication(); Connect("localhost", 5100, out outputAdmin, out inputAdmin); // CfgSettings.WritePathToFile("path_to_config.txt", rawpath); //if (!_readCfg) System.Windows.MessageBox.Show("Invalid configuration file"); //else { ConfigList.DataContext = Config; _agentDataDictionary = new AgentDataDictionary(Config); _statePeriod = SpeedSlider.Value; } AuctionsLabel.Header = "{Special items}"; LoadAndSetup(Config); SetBindings(); SetUI(); //RunRegistration(); //RunSimulation(); //AgentDataDictionary = new AgentDataDictionary(@"D:\#Recent_desktop\UNI\PES602\DMG\dammage 1.0\domains\english.pl"); this.Title = "MultiAgentz Visualization - " + Config.HistPath; } }