Exemplo n.º 1
0
        public virtual void Close(string Reason, bool Retry = true)
        {
            if (isClosed)
            {
                return;
            }

            isClosed = true;

            if ((Socket != null) && (Socket.Connected))
            {
                // Write("Close socket: " + Reason);

                try
                {
                    Send(new sMsg("logout", Reason));
                }
                catch { }

                Socket.Close(Reason, false);
                Socket = null;
            }

            Raise_Closed(new CloseArgs(Reason, Retry));
        }
Exemplo n.º 2
0
        private SocketArgs Connect(Socket Socket, Peer Peer, bool isSecure, bool isLocal)
        {
            SocketInterface sI = Sockets.Create(Socket, Peer, isSecure, isLocal);

            sI.Init();

            return(new SocketArgs(sI));
        }
Exemplo n.º 3
0
        public void Start(SocketInterface tSocket)
        {
            this.Socket = tSocket;

            this.Socket.Closed     += Raw_Closed;
            this.Socket.Received   += Raw_Received;
            this.Socket.Connection += Raw_Connected;

            this.Socket.Init();
        }
Exemplo n.º 4
0
        private void Completed(object sender, SocketAsyncEventArgs e)
        {
            if (e.SocketError != SocketError.Success)
            {
                Close(e.SocketError.ToString(), true);
                return;
            }

            SocketInterface tSocket = e.UserToken as SocketInterface;

            Start(tSocket);
        }
Exemplo n.º 5
0
        public RemoteOperationMaster(MESSAGE_FRAME_TYPE_T frameType, MESSAGE_DATA_CODE_T dataCode, bool dedicationR, SocketInterface sc, ref DESTINATION_ADDRESS_T destination, int sendBufferSize = 4096, int receiveBufferSize = 4096, object sync = null)
        {
            __socket             = sc;
            __frame_type         = frameType;
            __data_code          = dataCode;
            __destination        = destination;
            __send_byte_array    = new byte[sendBufferSize];
            __receive_byte_array = new byte[receiveBufferSize];
            __sync_object        = sync ?? new object();

            switch (frameType, dataCode, dedicationR)
            {
Exemplo n.º 6
0
        public async Task <DATA_SYNCHRONIZER_STATE_T> Stop()
        {
            __sync_operation_access_lock.Wait();
            try
            {
                switch (State)
                {
                case DATA_SYNCHRONIZER_STATE_T.READY:
                    //throw new InvalidOperationException("The data synchronization thread has not started yet.");
                    return(DATA_SYNCHRONIZER_STATE_T.READY);

                case DATA_SYNCHRONIZER_STATE_T.CONNECTED:
                    __stop_event.Set();
                    break;

                case DATA_SYNCHRONIZER_STATE_T.EXCEPTION:
                    __stop_event.Reset();
                    break;
                }

                if (__data_sync_thread != null)
                {
                    await Task.Run(() => __data_sync_thread.Join());

                    __data_sync_thread = null;
                }
                if (__io != null)
                {
                    __io.Dispose();
                    __io = null;
                }
                State = DATA_SYNCHRONIZER_STATE_T.READY;
                return(DATA_SYNCHRONIZER_STATE_T.READY);
            }
            finally
            {
                __sync_operation_access_lock.Release();
            }
        }
Exemplo n.º 7
0
        public void Start()
        {
            log.Info("Starting WebService from " + this.Name + "... ");

            this.TagsWebService.Start();

            log.Info("WebService from project " + this.Name + " is started. ");

            log.Info("Starting TCP/IP interface... ");

            //RegisterSocketInterface();
            SocketInterface.Start(this);

            log.Info("TCP/IP interface is started. ");

            foreach (DataSource ds in this.Datasources)
            {
                log.Info("Starting DataSource " + ds.Name + "... ");

                ds.Open();

                log.Info("DataSource " + ds.Name + " is started. ");
            }
        }
Exemplo n.º 8
0
        private async void StartSteamServer(CancellationTokenSource source)
        {
            var token = source.Token;

            void InitializeSteamServer()
            {
                const int GAME_PORT  = 30001;
                const int APP_ID     = 480;
                const int QUERY_PORT = GAME_PORT + 1;

                Console.WriteLine($"########### STARTING STEAM SREVER ##################");
                SteamServerInit serverInit = new SteamServerInit("TestInitSteamServer", "TestInitSteamServer TEST")
                {
                    GamePort      = GAME_PORT,
                    Secure        = true,
                    QueryPort     = QUERY_PORT,
                    VersionString = "0.0.0.1"
                };

                try
                {
                    //SteamServer.DedicatedServer = true;

                    SteamServer.OnCallbackException          += OnCallbackException;
                    SteamServer.OnSteamServerConnectFailure  += OnSteamServerConnectFailure;
                    SteamServer.OnSteamServersConnected      += OnSteamServersConnected;
                    SteamServer.OnSteamServersDisconnected   += OnSteamServersDisconnected;
                    SteamServer.OnValidateAuthTicketResponse += OnValidateAuthTicketResponse;
                    SteamServer.Init(APP_ID, serverInit);
                    SteamServer.DedicatedServer = true;
                    SteamServer.LogOnAnonymous();
                    SocketInterface socket = SteamNetworkingSockets.CreateNormalSocket <SocketInterface>(NetAddress.AnyIp(GAME_PORT));
                }
                catch (System.Exception e)
                {
                    Console.WriteLine($"#### SteamServer e:{e.Message}\n:{e.StackTrace}");
                    // Couldn't init for some reason (dll errors, blocked ports)
                    SteamServer.Shutdown();
                }
                Console.WriteLine($"#### SteamServer IsValid:{SteamServer.IsValid} IsLogedOn:{SteamServer.LoggedOn}");
            }

            void UpdateSteamServerCallbacks()
            {
                const long UPDATE_INTERVAL_IN_MS = 1000;
                long       lastTimeInMs          = long.MinValue;
                long       currentTimeInMs;

                try
                {
                    while (true)
                    {
                        token.ThrowIfCancellationRequested();

                        if (lastTimeInMs + UPDATE_INTERVAL_IN_MS < (currentTimeInMs = DateTime.UtcNow.ToTotalMillisUTC()))
                        {
                            lastTimeInMs = currentTimeInMs;
                            Console.WriteLine($"\tSteamServer Updating {lastTimeInMs}");
                            SteamServer.RunCallbacks();
                        }
                    }
                }
                finally
                {
                    SteamServer.Shutdown();
                    Console.WriteLine($"#### SteamServer Shutdown");
                }
            }

            await Task.Run(() => InitializeSteamServer());

            await Task.Factory.StartNew((x) => UpdateSteamServerCallbacks(), token, TaskCreationOptions.LongRunning);
        }
Exemplo n.º 9
0
 public SocketArgs(SocketInterface Socket)
 {
     this.Socket = Socket;
 }
Exemplo n.º 10
0
 public PacketPool(SocketInterface s)
 {
     socket = s;
 }
Exemplo n.º 11
0
        private async void CommunicationTest_Click(object sender, RoutedEventArgs e)
        {
            if (__property_error_counter != 0)
            {
                HandyControl.Controls.MessageBox.Show(this, "At least one user input field is invalid.", "Error Message", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                var             property = DataContext as TargetPropertyDataModel;
                SocketInterface com      = null;
                IsEnabled = false;
                _BusyIndicator.Visibility = Visibility.Visible;
                try
                {
                    DESTINATION_ADDRESS_T destination = new DESTINATION_ADDRESS_T(
                        property.NetworkNumber, property.StationNumber, property.ModuleIONumber,
                        property.MultidropNumber, property.ExtensionStationNumber);

                    if (property.UDPTransportLayer == true)
                    {
                        com = new UDP(new System.Net.IPEndPoint(property.SourceIPv4, property.SourcePort),
                                      new System.Net.IPEndPoint(property.DestinationIPv4, property.DestinationPort),
                                      property.ReceiveBufferSize, property.SendTimeoutValue, property.ReceiveTimeoutValue);
                    }
                    else
                    {
                        com = new TCP(new System.Net.IPEndPoint(property.SourceIPv4, 0),
                                      new System.Net.IPEndPoint(property.DestinationIPv4, property.DestinationPort),
                                      property.SendTimeoutValue, property.ReceiveTimeoutValue);
                        //__tcp.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 0));
                        await Task.Run(() => (com as TCP).Connect());
                    }

                    var master = new RemoteOperationMaster(property.FrameType, property.DataCode, property.R_DedicatedMessageFormat, com, ref destination,
                                                           property.SendBufferSize, property.ReceiveBufferSize, null);


                    (ushort end, string name, ushort code) = await master.ReadTypeNameAsync(property.MonitoringTimer);

                    if (end == (ushort)RESPONSE_MESSAGE_ENDCODE_T.NO_ERROR)
                    {
                        HandyControl.Controls.MessageBox.Show(this, $"Communication success, the destination device is { name.Trim()} (0x{code:X4}).", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    else
                    {
                        HandyControl.Controls.MessageBox.Show(this, $"The destination device returns end code 0x{end:X4}.", "Warning Message", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }
                catch (SLMPException ex)
                {
                    HandyControl.Controls.MessageBox.Show(this, "At least one unexpected error occured while doing communication test.\n" + ex.Message, "Error Message", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                finally
                {
                    _BusyIndicator.Visibility = Visibility.Hidden;
                    IsEnabled = true;
                    if (com != null)
                    {
                        com.Dispose();
                    }
                    com = null;
                }
            }
        }
Exemplo n.º 12
0
        public async Task <DATA_SYNCHRONIZER_STATE_T> Startup(TargetPropertyDataModel target)
        {
            __sync_operation_access_lock.Wait();
            try
            {
                switch (State)
                {
                case DATA_SYNCHRONIZER_STATE_T.CONNECTED:
                    //throw new InvalidOperationException("The data synchronization thread is still running.");
                    return(DATA_SYNCHRONIZER_STATE_T.CONNECTED);

                case DATA_SYNCHRONIZER_STATE_T.EXCEPTION:
                    if (__data_sync_thread != null)
                    {
                        __data_sync_thread.Join();
                        __data_sync_thread = null;
                    }
                    break;

                case DATA_SYNCHRONIZER_STATE_T.READY:
                    break;
                }

                __stop_event.Reset();
                if (target.UDPTransportLayer)
                {
                    __io = new UDP(new System.Net.IPEndPoint(target.SourceIPv4, target.SourcePort),
                                   new System.Net.IPEndPoint(target.DestinationIPv4, target.DestinationPort),
                                   target.ReceiveBufferSize, target.SendTimeoutValue, target.ReceiveTimeoutValue);
                }
                else
                {
                    __io = new TCP(new System.Net.IPEndPoint(target.SourceIPv4, 0),
                                   new System.Net.IPEndPoint(target.DestinationIPv4, target.DestinationPort),
                                   target.SendTimeoutValue, target.ReceiveTimeoutValue);
                }
                DESTINATION_ADDRESS_T destination = new DESTINATION_ADDRESS_T(target.NetworkNumber, target.StationNumber, target.ModuleIONumber, target.MultidropNumber, target.ExtensionStationNumber);

                DeviceAccessMaster master = new DeviceAccessMaster(target.FrameType, target.DataCode, target.R_DedicatedMessageFormat, __io,
                                                                   ref destination, target.SendBufferSize, target.ReceiveBufferSize);

                if (__io is TCP)
                {
                    State = DATA_SYNCHRONIZER_STATE_T.CONNECTING;
                    await Task.Run(() => (__io as TCP).Connect());
                }

                __heartbeat_counter = 0;
                __data_sync_thread  = new Thread(new ParameterizedThreadStart(__data_sync_routine));
                __data_sync_thread.Start(Tuple.Create(master, (ushort)(target.MonitoringTimer / 250), target.PollingInterval));
                State            = DATA_SYNCHRONIZER_STATE_T.CONNECTED;
                ExceptionMessage = "";
                return(DATA_SYNCHRONIZER_STATE_T.CONNECTED);
            }
            catch (SLMPException ex)
            {
                State            = DATA_SYNCHRONIZER_STATE_T.EXCEPTION;
                ExceptionMessage = ex.Message;
                return(DATA_SYNCHRONIZER_STATE_T.EXCEPTION);
            }
            finally
            {
                __sync_operation_access_lock.Release();
            }
        }