コード例 #1
0
    public void Start(int port = 0)
    {
        _listenning     = false;
        _newConnections = new Queue <NewConnection>();
        _clients        = new Dictionary <int, ORTCPClient>();

        if (port != 0)
        {
            StartListening(port);
        }
        else
        {
            StartListening();
        }

        Observable
        .Interval(TimeSpan.FromSeconds(1))
        .Where(_ => _newConnections.Count > 0)
        .Subscribe(_ =>
        {
            //Debug.Log(Thread.CurrentThread.ManagedThreadId);
            NewConnection newConnection = _newConnections.Dequeue();
            ORTCPClient client          = ORTCPClient.CreateInstance("ORMultiServerClient", newConnection.tcpClient, this, port);

            int clientID = SaveClient(client);
            ORTCPEventParams eventParams = new ORTCPEventParams();
            eventParams.eventType        = ORTCPEventType.Connected;
            eventParams.client           = client;
            eventParams.clientID         = clientID;
            eventParams.socket           = newConnection.tcpClient;
            Console.BackgroundColor      = ConsoleColor.Cyan;
            Console.ForegroundColor      = ConsoleColor.Black;
            Console.WriteLine("[TCPServer] New client connected");
        });
    }
コード例 #2
0
ファイル: CQHub.cs プロジェクト: wilson0x4d/shenc
        public async Task <CQConnection> ConnectTo(string hostport)
        {
            var parts      = hostport.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
            var hostName   = parts[0];
            var portNumber = parts.Length > 1 ? int.Parse(parts[1]) : 18593;

            var connection = await CQConnection.Create(_crypt, hostName, portNumber, _rsa, _onStatusChange);

            ValidateWhitelistAndSetAlias(connection);

            lock (_connections)
            {
                // NOTE: prior connections to same peer are not removed, by design
                _connections.Add(connection);
            }
            try
            {
                NewConnection?.Invoke(this, new CQConnectionEventArgs
                {
                    Connection = connection
                });
            }
            catch (Exception ex)
            {
                ex.Log();
            }
            $"Connected to [{connection}]".Log();

            return(connection);
        }
コード例 #3
0
        private void miNewConnection_Click(object sender, RoutedEventArgs e)
        {
            // open new connection from
            NewConnection nc = new NewConnection();

            nc.ShowDialog();
        }
コード例 #4
0
        void newConnection_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            NewConnection newConnection = (NewConnection)sender;

            switch (newConnection.Status)
            {
            case Classes.WindowResult.Created:
                this.Project.Connections.Add(newConnection.ConnectionConfiguration);
                break;

            case Classes.WindowResult.Canceled:
                if (newConnection.ConnectionConfiguration == null || newConnection.OriginalConnectionConfiguration == null)
                {
                    return;
                }

                object revertedConfiguration = ConfigurationSerializer.DeserializeObject(
                    newConnection.OriginalConnectionConfiguration,
                    newConnection.ConnectionConfiguration.GetType(),
                    moduleLoader.GetModuleTypeList()
                    );

                ((ConnectionConfigurationBase)revertedConfiguration).ModuleDescription = newConnection.ConnectionConfiguration.ModuleDescription;

                int indexConfiguration = this.Project.Connections.IndexOf(newConnection.ConnectionConfiguration);
                this.Project.Connections[indexConfiguration] = revertedConfiguration as ConnectionConfigurationBase;
                break;
            }
        }
コード例 #5
0
        /*接收新的连接*/
        private void OnAcceptNewConnection(object sender, SocketAsyncEventArgs e)
        {
            /*新连接的socket对象*/
            var socket = e.AcceptSocket;

            /*继续接收*/
            startAccept(e);

            /*连接数+1*/
            Interlocked.Increment(ref connectionCount);


            /*尝试取出一个异步完成套接字*/
            if (!receiveAsyncEventQueue.TryDequeue(out var socketReceiveAsync))
            {
                socketReceiveAsync            = new SocketAsyncEventArgs();
                socketReceiveAsync.Completed += SocketAsync_Receive_Completed;
                socketReceiveAsync.SetBuffer(new byte[bufferLength], 0, bufferLength);
            }

            /*创建一个客户端*/
            var connection = new SocketClient
            {
                SocketAsyncEvent = socketReceiveAsync,
                RemoteEndPoint   = socket.RemoteEndPoint,
                Socket           = socket,
            };

            socketReceiveAsync.UserToken = connection;
            NewConnection?.Invoke(this, connection);
            StartReceive(connection);
        }
コード例 #6
0
        virtual internal void OnNewConnection(INetworkNode Remote)
        {
            if (Remote == null)
            {
                return;
            }

            if (!Remotes.Contains(Remote))
            {
                Remotes.Add(Remote);
            }

            if (NewConnection == null)
            {
                return;
            }

            Task.Run(() =>
            {
                NewConnection?.Invoke(this, new InternetConnectionEventArgs
                {
                    Local  = this,
                    Remote = Remote
                });
            });
        }
コード例 #7
0
    private void Start()
    {
        _listenning     = false;
        _newConnections = new Queue <NewConnection>();
        _clients        = new Dictionary <int, ORTCPClient>();
        StartListening();

        Observable
        .EveryUpdate()
        .Where(_ => _newConnections.Count > 0)
        .Subscribe(_ =>
        {
            //Debug.Log(Thread.CurrentThread.ManagedThreadId);
            NewConnection newConnection = _newConnections.Dequeue();
            ORTCPClient client          = ORTCPClient.CreateInstance("ORMultiServerClient", newConnection.tcpClient, this);


            int clientID = SaveClient(client);
            ORTCPEventParams eventParams = new ORTCPEventParams();
            eventParams.eventType        = ORTCPEventType.Connected;
            eventParams.client           = client;
            eventParams.clientID         = clientID;
            eventParams.socket           = newConnection.tcpClient;
            if (verbose)
            {
                print("[TCPServer] New client connected");
            }
        });
    }
コード例 #8
0
        async Task ConnectionWaitAsync()
        {
            _logger.LogInformation("Server: Waiting for connection");
            if (_listener is null)
            {
                return;
            }
            var tcs = new TaskCompletionSource <int>();

            await using (Token.Register(tcs.SetCanceled))
            {
                while (!Token.IsCancellationRequested)
                {
                    var t = _listener.AcceptTcpClientAsync();
                    if ((await Task.WhenAny(t, tcs.Task)).IsCanceled)
                    {
                        break;
                    }
                    try
                    {
                        using var client = t.Result;
                        var message = await JsonSerializer.DeserializeAsync <Message>(client.GetStream());

                        var endPoint = client.Client.RemoteEndPoint;
                        await(NewConnection?.Invoke(endPoint as IPEndPoint, message.Type) ?? Task.CompletedTask);
                        await(MessageReceived?.Invoke(message, endPoint as IPEndPoint) ?? Task.CompletedTask);
                    }
                    catch (SocketException e)
                    {
                        _logger.LogError("Server: Error on ConnectionWaiting.", e);
                    }
                }
            }
            _listener.Stop();
        }
コード例 #9
0
    void Start()
    {
        isListening    = false;
        newConnections = new Queue <NewConnection>();
        clients        = new Dictionary <int, ORTCPClient>();
        StartListening();

        Observable
        .Interval(TimeSpan.FromSeconds(1))
        .Where(x => newConnections.Count > 0)
        .Subscribe(x =>
        {
            NewConnection newConnection = newConnections.Dequeue();
            ORTCPClient client          = ORTCPClient.CreateClientInstance("MultiserverClient", newConnection.tcpClient, this);

            int clientId = SaveClient(client);
            TCPEventParams eventParams = new TCPEventParams();
            eventParams.eventType      = eTCPEventType.Connected;
            eventParams.client         = client;
            eventParams.clientID       = clientId;
            eventParams.socket         = newConnection.tcpClient;

            if (verbose)
            {
                print("[TCPServer] New Client Connected: " + client.name);
            }
        });
    }
コード例 #10
0
ファイル: WebSocketConnection.cs プロジェクト: qdraw/starsky
        public async Task ReceiveMessagesUntilCloseAsync()
        {
            try
            {
                NewConnection?.Invoke(this, EventArgs.Empty);
                byte[] receivePayloadBuffer = new byte[_receivePayloadBufferSize];
                WebSocketReceiveResult webSocketReceiveResult =
                    await _webSocket.ReceiveAsync(new ArraySegment <byte>(receivePayloadBuffer),
                                                  CancellationToken.None);

                CloseStatus = await GetMessage(webSocketReceiveResult);

                CloseStatusDescription = webSocketReceiveResult.CloseStatusDescription;
            }
            catch (WebSocketException webSocketException) when(webSocketException
                                                               .WebSocketErrorCode ==
                                                               WebSocketError.ConnectionClosedPrematurely)
            {
                Console.WriteLine(
                    "connection ConnectionClosedPrematurely (exception is catch-ed) ");
            }
            catch (OperationCanceledException)
            {
                // Happens when the application closes
                Console.WriteLine("connection OperationCanceledException (exception is catch-ed)");
            }
        }
コード例 #11
0
        private void StartListenRequests()
        {
            _logger.Trace("Запуск прослушивания подключений...");

            while (true)
            {
                try
                {
                    var    handler = _serverSocket.Accept();
                    var    builder = new StringBuilder();
                    int    bytes   = 0;
                    byte[] data    = new byte[256];

                    do
                    {
                        bytes = handler.Receive(data);
                        builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
                    }while (handler.Available > 0);

                    _logger.Trace("Обнаружено новое подключение...");

                    var message = builder.ToString();
                    NewConnection?.Invoke(message, handler);
                }
                catch (Exception e)
                {
                    _logger.Error($"Произошла ошибка при получении запроса: {e.Message}");
                }
            }
        }
コード例 #12
0
        /// <summary>
        /// Adds to the Inbound Requests que and adds to the connections list if a matching IP does not exist.
        /// </summary>
        /// <param name="from">IPAddress of the request</param>
        private static void AddInboundRequest(object from)
        {
            IPAddress sender = (IPAddress)from;
            bool      found  = false;

            foreach (ConnectionInfo connection in connections)
            {
                if (connection.address.Equals(sender))
                {
                    found = true;
                    if (!InboundReq.Contains(connection))
                    {
                        InboundReq.Add(connection);
                        connection.InvokeInboundRequest();
                    }
                    else if (OutboundReq.Contains(connection))
                    {
                        GameConnection.RequestGame(connection);
                    }
                    break;
                }
            }

            if (found == false && NewConnection != null)
            {
                ConnectionInfo connection = new ConnectionInfo()
                {
                    address = sender, displayName = "Unknown"
                };
                connections.Add(connection);
                InboundReq.Add(connection);
                NewConnection.Invoke(null, connection);
                connection.InvokeInboundRequest();
            }
        }
コード例 #13
0
ファイル: TCPService.cs プロジェクト: tgiphil/GoTraxx
 public TCPService(int portNumber, int maxConnections, NewConnection newConnection, GetCount getCount)
 {
     PortNumber = portNumber;
     MaxConnections = maxConnections;
     AcceptedConnections = 0;
     OnNewConnection = newConnection;
     GetConnectCount = getCount;
 }
コード例 #14
0
 public TCPService(int portNumber, int maxConnections, NewConnection newConnection, GetCount getCount)
 {
     PortNumber          = portNumber;
     MaxConnections      = maxConnections;
     AcceptedConnections = 0;
     OnNewConnection     = newConnection;
     GetConnectCount     = getCount;
 }
コード例 #15
0
        protected override void OnStartup(StartupEventArgs e)
        {
            InDesignMode = false;
            Current      = (App)Application.Current;
            Res          = new AppResources();

            EnsureUserFolders();

            Task.Run(() => Firewall.Instance.GrantAuthorizationToSelf());

            var firstArg = e.Args.FirstOrDefault();

            if (firstArg?.Equals("-nonew", StringComparison.OrdinalIgnoreCase) == true)
            {
                new MainWindow().Show();
            }
            else if (firstArg?.Equals("-settings", StringComparison.OrdinalIgnoreCase) == true && e.Args.Length == 2)
            {
                var cs      = ConnectionSettings.Deserialize(File.ReadAllBytes(e.Args[1]));
                var session = cs.CreateSession();
                if (session != null)
                {
                    var mainWindow = new MainWindow();
                    mainWindow.Show();
                    mainWindow.AddSessionAndStart(session);
                }
            }
            else
            {
                Rect rect    = Rect.Empty;
                var  session = SessionFromArgs(e.Args);

                if (session == null)
                {
                    ShutdownMode = ShutdownMode.OnExplicitShutdown;
                    var dlg = new NewConnection()
                    {
                        ShowInTaskbar = true, Title = "Swiddler", WindowStartupLocation = WindowStartupLocation.CenterScreen
                    };
                    dlg.ShowDialog();
                    session = dlg.Result;
                    rect    = new Rect(dlg.Left, dlg.Top, dlg.Width, dlg.Height);
                }

                if (session != null)
                {
                    ShutdownMode = ShutdownMode.OnLastWindowClose;
                    var mainWindow = new MainWindow();
                    if (!rect.IsEmpty)
                    {
                        mainWindow.Left = (rect.Width - mainWindow.Width) / 2.0 + rect.Left; // center of closed NewConnection dialog
                        mainWindow.Top  = (rect.Height - mainWindow.Height) / 2.0 + rect.Top;
                    }
                    mainWindow.Show();
                    mainWindow.AddSessionAndStart(session);
                }
            }
        }
コード例 #16
0
        public static void FinishStreamWithUser(IAsyncResult resobj)
        {
            NewConnection CONNECTION = (NewConnection)resobj.AsyncState;

            if (CONNECTION.Client.Connected)
            {
                CONNECTION.StopThreading();
            }
        }
コード例 #17
0
 private void HandshakeFinished(IAsyncResult status)
 {
     TrySocketAction(r =>
     {
         r.EndSend(status);
         r.BeginReceive(ReceivedDataBuffer, 0, ReceivedDataBuffer.Length, 0, new AsyncCallback(Read), null);
         NewConnection?.Invoke(this, EventArgs.Empty);
     });
 }
コード例 #18
0
ファイル: MockProtocol.cs プロジェクト: Falrach94/Plattform
 public Task NewConnectionAsync(Connection connection)
 {
     Workload();
     if (NewConnection == null)
     {
         return(Task.CompletedTask);
     }
     return(NewConnection?.Invoke(connection));
 }
コード例 #19
0
        public Task NewConnectionAsync(ObjectPath device, CloseSafeHandle fileDescriptor, IDictionary <string, object> properties)
        {
            SocketState     = SocketStates.Connected;
            _fileDescriptor = fileDescriptor;
            Log.Debug("Linux.BluetoothSocket: Connected to profile");

            Stream = new UnixStream(fileDescriptor.DangerousGetHandle().ToInt32());

            Task.Run(() => NewConnection?.Invoke(device, _fileDescriptor, properties));
            return(Task.CompletedTask);
        }
コード例 #20
0
        private void lbConnections_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ConnectionConfigurationBase connectionConfiguration = ((ListBox)sender).SelectedItem as ConnectionConfigurationBase;

            if (connectionConfiguration != null)
            {
                string        orginalConnectionConfiguration = ConfigurationSerializer.SerializeObject(connectionConfiguration, this.moduleLoader.GetModuleTypeList());
                NewConnection newConnection = new NewConnection(this.moduleLoader.Modules, connectionConfiguration, orginalConnectionConfiguration);
                ShowNewConnectionWindow(newConnection);
            }
        }
コード例 #21
0
        private void HandleConnectionPacket(TcpPacket tcpPacket, ConnectionId connectionId)
        {
            var connection = new TcpConnection(connectionId, tcpPacket.SequenceNumber);

            NewConnection?.Invoke(connection);

            if (connection.HasSubscribers)
            {
                _connections[connectionId] = connection;
            }
        }
コード例 #22
0
ファイル: DelegateSniffer.cs プロジェクト: qipa/delegate
        private void HandleTcpDataReceived(TcpConnection connection, ArraySegment <byte> data)
        {
            if (data.Count == 0)
            {
                return;
            }
            if (_isNew.Contains(connection))
            {
                if (_serversByIp.ContainsKey(connection.Source.Address.ToString()) &&
                    data.Array.Skip(data.Offset).Take(4).SequenceEqual(new byte[] { 1, 0, 0, 0 }))
                {
                    _isNew.Remove(connection);
                    var server = _serversByIp[connection.Source.Address.ToString()];
                    _serverToClient = connection;
                    _clientToServer = null;

                    _decrypter = new ConnectionDecrypter();
                    _decrypter.ClientToServerDecrypted += HandleClientToServerDecrypted;
                    _decrypter.ServerToClientDecrypted += HandleServerToClientDecrypted;

                    _messageSplitter = new MessageSplitter();
                    _messageSplitter.MessageReceived += HandleMessageReceived;
                    NewConnection?.Invoke(server);
                }
                if (_serverToClient != null && _clientToServer == null &&
                    (_serverToClient.Destination.Equals(connection.Source) &&
                     _serverToClient.Source.Equals(connection.Destination)))
                {
                    _isNew.Remove(connection);
                    _clientToServer = connection;
                }
            }

            if (!(connection == _clientToServer || connection == _serverToClient))
            {
                return;
            }
            if (_decrypter == null)
            {
                return;
            }
            var dataArray = data.Array.Skip(data.Offset).Take(data.Count).ToArray();

            if (connection == _clientToServer)
            {
                _decrypter.ClientToServer(dataArray);
            }
            else
            {
                _decrypter.ServerToClient(dataArray);
            }
        }
コード例 #23
0
 virtual internal void OnNewConnection(INetworkNode Remote)
 {
     if (NewConnection != null)
     {
         Task.Run(() =>
         {
             NewConnection?.Invoke(this, new InternetConnectionEventArgs
             {
                 Local  = this,
                 Remote = Remote
             });
         });
     }
 }
コード例 #24
0
        private void AcceptConnectCallback(IAsyncResult ar)
        {
            Listener = (Socket)ar.AsyncState;

            //acknowledge the connection
            Socket incomingSocket = null;

            try
            {
                incomingSocket = Listener.EndAccept(ar);
            }
            catch
            {
                ReportError?.Invoke("EndAccept failed on incoming connection", "");
            }

            //put the listener back to listening
            Listener.BeginAccept(new AsyncCallback(AcceptConnectCallback), Listener);

            if (incomingSocket == null)
            {
                return;
            }
            IPEndPoint ep = (IPEndPoint)incomingSocket.RemoteEndPoint;

            TConnection C = new TConnection();

            C.Setup(incomingSocket, ep.Address, ep.Port, ConnectionBufSize);

            if (AllConnections.ContainsKey(C.Address) == false)
            {
                AllConnections.Add(C.Address, C);
                AllConnectionsList.Add(C);
            }

            //Signal that a new connection has been created
            NewConnection?.Invoke(C);

            //configure the socket to receive incoming data and arm the data reception event
            try
            {
                C.ConnectionSocket.BeginReceive(C.IncomingData, 0, C.IncomingData.Length, 0, new AsyncCallback(ReadCallback), C.Address);
            }
            catch
            {
                ReportError?.Invoke("BeginReceive failed on new connection", C.Address);
            }
        }
コード例 #25
0
ファイル: Server.cs プロジェクト: webconfig/Ballz
        public void Update(GameTime time)
        {
            NetIncomingMessage im;

            while ((im = Peer.ReadMessage()) != null)
            {
                switch (im.MessageType)
                {
                case NetIncomingMessageType.StatusChanged:
                    NetConnectionStatus status = (NetConnectionStatus)im.ReadByte();

                    string reason = im.ReadString();

                    if (!GameRunning && status == NetConnectionStatus.Connected)
                    {
                        Sync.AddConnection(im.SenderConnection);
                        NewConnection?.Invoke(this, im.SenderConnection);
                    }

                    break;

                case NetIncomingMessageType.DiscoveryRequest:
                    // Respond to discovery requests with a json-serialized game info
                    // But only send the non-secret parts
                    var publicInfo     = GameInfo.PublicInfo();
                    var serializedInfo = JsonConvert.SerializeObject(publicInfo);
                    var response       = Peer.CreateMessage();
                    response.Write(serializedInfo);
                    Peer.SendDiscoveryResponse(response, im.SenderEndPoint);
                    break;

                case NetIncomingMessageType.Data:
                    Sync.ReadMessage(im);
                    break;
                }

                Peer.Recycle(im);
            }

            if (GameRunning && WorldSyncTimer.ElapsedMilliseconds > Network.WorldSyncIntervalMs)
            {
                // Send full world state on every frame.
                //Todo: Only send updates for world synchronization
                SendWorldState();
                WorldSyncTimer.Restart();
            }
        }
コード例 #26
0
ファイル: Controller.cs プロジェクト: smeoow/Naive
 private void onConnectionBegin(InConnection inc, IAdapter outAdapter)
 {
     if (LoggingLevel <= Logging.Level.None)
     {
         debug($"'{inc.InAdapter.Name}' {inc} -> '{outAdapter.Name}'");
     }
     try {
         lock (InConnectionsLock) {
             inc.InAdapter.GetAdapter().CreatedConnections++;
             _totalHandledConnections++;
             InConnections.Add(inc.Id, inc);
             NewConnection?.Invoke(inc);
         }
     } catch (Exception e) {
         Logger.exception(e, Logging.Level.Error, "event NewConnection");
     }
 }
コード例 #27
0
        protected void AcceptHandler(IAsyncResult ar)
        {
            // Signal the main thread to continue.
            _connAccepted.Set();

            // Get the socket that handles the client request.
            Socket clientSock = this._socket.EndAccept(ar);

            _logger.Debug($"Client connected from {clientSock.RemoteEndPoint}");

            // Create client
            InputConnection client = new InputConnection(clientSock);

            // Emit events and run default class handler
            this.OnConnection(client);
            NewConnection?.Invoke(client);
        }
コード例 #28
0
    private void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(this.gameObject);
        }
        else
        {
            _instance = this;
        }
        //debug binding
        Observable.EveryUpdate()
        .Select(_ => GameManager.TargetObject_External)
        .DistinctUntilChanged()
        .Subscribe(_ => verbose = (GameManager.TargetObject_External & TargetObject.TCP) == TargetObject.TCP)
        .AddTo(gameObject);

        _listenning     = false;
        _newConnections = new Queue <NewConnection>();
        _clients        = new Dictionary <int, ORTCPClient>();
        StartListening();

        Observable
        .EveryUpdate()
        .Where(_ => _newConnections.Count > 0)
        .Subscribe(_ =>
        {
            //Debug.Log(Thread.CurrentThread.ManagedThreadId);
            NewConnection newConnection = _newConnections.Dequeue();
            ORTCPClient client          = ORTCPClient.CreateInstance("ORMultiServerClient", newConnection.tcpClient, this);


            int clientID = SaveClient(client);
            ORTCPEventParams eventParams = new ORTCPEventParams();
            eventParams.eventType        = ORTCPEventType.Connected;
            eventParams.client           = client;
            eventParams.clientID         = clientID;
            eventParams.socket           = newConnection.tcpClient;
            if (verbose)
            {
                print("[TCPServer] New client connected");
            }
        });
    }
コード例 #29
0
        private void InitialiseSocketHandler(TcpClient socket)
        {
            var handler = new FtpSocketHandler(m_fileSystemClassFactory, m_nId);

            handler.UserLoginEvent  += UserLoginEvent;
            handler.UserLogoutEvent += UserLogoutEvent;
            // get encoding for the socket connection
            handler.Start(socket, m_encoding);

            m_apConnections.Add(handler);

            numberOfConnections = m_apConnections.Count;

            Trace.WriteLine($"Add a new handler, current connection number is {numberOfConnections}", "Information");

            handler.Closed += Handler_Closed;

            NewConnection?.Invoke(m_nId);
        }
コード例 #30
0
        private void ShowConnectionDialog(UnicornConnection info = null)
        {
            var shouldUpdate = SelectedConnection != null;

            info = info ?? new UnicornConnection();
            var newConnection = new NewConnection(info);

            if (newConnection.ShowModal() != true)
            {
                return;
            }

            LoadConnections();
            if (shouldUpdate)
            {
                SelectedConnection = null;
                SelectedConnection = info;
            }
        }
コード例 #31
0
        protected virtual ServerPlayer AcceptTCPConnection(TCPConnectionManager.PendingClient client)
        {
            ServerPlayer p = NewPlayerRecord(client);

            Logger.Log3("Socket " + p.GetTCPRemoteAddresString() + " Connected ");

            p.Disconnected += P_Disconnected;

            p.PlayerID = FindPlayerID();
            if (p.PlayerID < 0)
            {
                return(null);
            }

            lock (ConnectedPlayers)
                ConnectedPlayers.Add(p.PlayerID, p);

            NewConnection?.Invoke(this, p);

            return(p);
        }
コード例 #32
0
        ///<summary>
        /// Default constructor for FerdaView class.
        ///</summary>
        ///<param name="locManager">
        /// Interface that takes care of the 
        ///localizacion in the application
        /// </param>
        ///<param name="svgMan">
        /// Interface for providing SVG graphics
        ///</param>
        ///<param name="menuDisp">Menu displayer</param>
        ///<param name="view">The view thath should be connected to this desktop</param>
        ///<param name="pm">The project manager of the application</param>
        ///<param name="arch">Control that displays the archive</param>
        ///<param name="provider">Provider of the icons</param>
        ///<param name="toolBar">Toolbar control</param>
        public FerdaDesktop(Menu.ILocalizationManager locManager,
            SVGManager svgMan, IMenuDisplayer menuDisp, ProjectManager.View view,
            ProjectManager.ProjectManager pm, Archive.IArchiveDisplayer arch,
            IIconProvider provider, IMenuDisplayer toolBar)
            : base()
        {
            //setting the icon
            this.provider = provider;

            //adding the localization
            localizationManager = locManager;
            ResManager = localizationManager.ResManager;

            //adding the svgManager
            svgManager = svgMan;

            //setting the menu displayer
            menuDisplayer = menuDisp;
            archiveDisplayer = arch;
            this.toolBar = toolBar;

            //Current view
            this.view = view;
            projectManager = pm;

            //name of the desktop
            Name = view.Name;

            //properties od the GraphControl to work propertly
            AllowMoveShape = true;
            AllowAddConnection = true;
            AllowAddShape = true;
            AllowDeleteShape = true;
            AllowDrop = true;
            AutoScroll = true;
            EnableContextMenu = true;
            EnableLayout = false;
            ShowGrid = false;
            Zoom = 1;
            RestrictToCanvas = false;
            this.ImeMode = System.Windows.Forms.ImeMode.On;

            //for now trial stuff
            BackgroundType = Netron.GraphLib.CanvasBackgroundTypes.Gradient;
            GradientTop = System.Drawing.Color.SkyBlue;

            //EventHandlers
            GotFocus += new EventHandler(FerdaDesktop_GotFocus);
            OnContextMenu += new MouseEventHandler(FerdaDesktop_ContextMenu);
            OnNewConnection += new NewConnection(FerdaDesktop_OnNewConnection);
            KeyPress += new KeyPressEventHandler(FerdaDesktop_KeyPress);
            OnFerdaMouseUp += new MouseEventHandler(FerdaDesktop_OnFerdaMouseUp);
            OnFerdaDeleteConnection += new FerdaConnection(FerdaDesktop_OnFerdaDeleteConnection);
            OnShapeRemoved += new NewShape(FerdaDesktop_OnShapeRemoved);

            //Setting the arrow for connections
            DefaultLineEnd = ConnectionEnds.RightFilledArrow;

            //Creation of the boxes and connections
            Adapt();
        }
コード例 #33
0
        /// <summary>
        /// Reacts to a click for a module asking for creation and adds the module
        /// to the view
        /// </summary>
        /// <param name="sender">Sender of the event</param>
        /// <param name="e">Event parameters</param>
        void Creation_Click(object sender, EventArgs e)
        {
            IBoxModule[] newBoxes = null;

            BoxNode bn;
            IBoxModule box;
            //this prevents executing anything when the event is not called from the
            //desktop (but from the main menu)
            if (Hover == null)
            {
                bn = SelectedShapes[0] as BoxNode;
                box = bn.Box;
            }
            else
            {
                bn = Hover as BoxNode;
                box = bn.Box;
            }

            foreach (ModulesAskingForCreation info in box.ModulesAskingForCreation)
            {
                if (info.label == sender.ToString())
                {
                    newBoxes = view.CreateBoxesAskingForCreation(info);
                    break;
                }
            }

            //adding the individual boxes so we dont have to adapt the whole
            //desktop
            foreach (IBoxModule b in newBoxes)
            {
                //adding the box
                BoxNode node = AddBox(b);

                Connector from = null;
                string socketName = string.Empty;

                foreach (ProjectManager.Connection con in view.Connections)
                {
                    //this is the right box (assuming there is only one box
                    //connected to the created box
                    if (con.ToBox == b)
                    {
                        from = FromConnector(con.FromBox);
                        socketName = con.ToSocket;
                    }
                }
                Connector to = ToConnector(b, socketName);

                //We have to remove the handler because it would create a connection
                //that is already there
                OnNewConnection -= new NewConnection(FerdaDesktop_OnNewConnection);

                //adding the connector
                AddEdge(from, to);

                //recreating the handler
                OnNewConnection += new NewConnection(FerdaDesktop_OnNewConnection);
            }
            archiveDisplayer.Adapt();
        }
コード例 #34
0
        ///<summary>
        ///Redraws all shapes and connections according to a new state in
        ///the view object
        ///</summary>
        ///<remarks>
        ///Dont know if the control will remember previous shapes and connections
        ///and ask for the changed or write the entire structure over again...
        ///</remarks>
        public void Adapt()
        {
            this.Hide();
            Nodes.Clear();
            selectedBoxes.Clear();

            //We have to remove the handler because it would create a connection
            //that is already there
            OnNewConnection -= new NewConnection(FerdaDesktop_OnNewConnection);

            //adding the boxes on the desktop
            foreach ( IBoxModule box in view.Boxes)
            {
                BoxNode boxNode = new BoxNode(this, box, SvgManager, view, ResManager);
                boxNode.X = view.GetPosition(box).X;
                boxNode.Y = view.GetPosition(box).Y;

                Nodes.Add(boxNode);
            }

            //adding the connections on the desktop
            foreach (ProjectManager.Connection con in view.Connections)
            {
                //finding the from and to connectors
                Connector from = FromConnector(con.FromBox);
                Connector to = ToConnector(con.ToBox, con.ToSocket);

                //adding the connector
                AddEdge(from, to);
            }
            this.Show();

            OnNewConnection += new NewConnection(FerdaDesktop_OnNewConnection);
        }