public void OnConnectionEstablished(object sender, EventArgs args) { DataSource ds = sender as DataSource; System.Diagnostics.Debug.WriteLine("Datasource " + ds + " started successfully"); ConnectionEstablished?.Invoke(sender, args); }
private async Task ListenForMessages() { while (!_cancellationToken.IsCancellationRequested) { var response = await Task.Run( async() => await _client.ReceiveAsync().ConfigureAwait(false), _cancellationToken ); Connected = true; _sendingPing = false; _noMessagesReceivedTimer.Stop(); _noMessagesReceivedTimer.Start(); var accMessage = AccApiResponse.Parse(response.Buffer); if (accMessage is RegistrationResponse registration) { ConnectionId = registration.ConnectionId; ConnectionEstablished?.Invoke(this, null); _registered = true; } // Trim out realtime responses as this generates too much noise if (!(accMessage is RealTimeUpdateResponse || accMessage is RealTimeCarUpdateResponse)) { Logger.Log($"Received {accMessage}", Severity.Verbose); } MessageReceived?.Invoke(this, accMessage); } }
public void Bind(WebSocket wsClient) { WsClient?.Dispose(); WsClient = wsClient; Init(); ConnectionEstablished?.Invoke(); }
/// <summary> /// Initialize a <see cref="HaConnection"/> with a list of <see cref="ManagedConnectionFactory"/> /// These connection factories are responsibile for creating <see cref="IConnection"/> to nodes in the clusters /// </summary> /// <param name="retryPolicy"></param> /// <param name="watcher"></param> /// <param name="connectionFactories"></param> public HaConnection(IRetryPolicy retryPolicy, IRabbitWatcher watcher, IList <ManagedConnectionFactory> connectionFactories) : base(retryPolicy, watcher) { _connectionFactories = new RoundRobinList <ConnectionFactory>(connectionFactories); ConnectionEstablished handler = (endpoint, virtualHost) => { if (_connectionFactories.All.Any(f => f.Endpoint + f.VirtualHost == endpoint + virtualHost)) { if (!IsConnected) { while (_connectionFactories.Current.Endpoint + _connectionFactories.Current.VirtualHost != endpoint + virtualHost) { //IF there are 2 different Tunnels using 2 HaConnection with 2 lists of cluster nodes in different orders: //Example: // ConnectionString1: host=q1;username=guest;password=guest|host=q2;username=guest;password=guest|host=q3;username=guest;password=guest // ConnectionString2: host=q2;username=guest;password=guest|host=q3;username=guest;password=guest|host=q1;username=guest;password=guest // When the first tunnel established the connection successfully to q1, it fires event and these lines of code is triggered. // The 2nd HaConnection needs to set it's _connectionFactories.Current to q1 established by other tunnel. Before changing, _connectionFactories.Current is q3 by the order in the ConnectionString2 _connectionFactories.GetNext(); } } FireConnectedEvent(); } }; ManagedConnectionFactory.ConnectionEstablished += handler; _unsubscribeEvents = () => { ManagedConnectionFactory.ConnectionEstablished -= handler; }; }
private void ProtocolClient_ConnectionEstablished(ProtocolClient sender) { lock (syncLock) { connectedClients.Add(sender); ConnectionEstablished?.Invoke(sender); } }
public void Bind(TcpClient tcpClient) { TCPClient?.Dispose(); TCPClient = tcpClient; DataStream = tcpClient.GetStream(); Init(); ConnectionEstablished?.Invoke(); }
public DynamicEndpoint(dynamic client) { this.client = client; ITransportationLayer transport = client; transport.ConnectionEstablished += () => ConnectionEstablished?.Invoke(); transport.ConnectionLost += () => ConnectionLost?.Invoke(); transport.ProviderDataReady += data => ProviderDataReady?.Invoke(data); }
/// <summary> /// Creates a new SpaceWars instance and attempts a connection to the given hostname. /// The connection established/failed delegates are used to notify of connection status. /// This instance should not be used until the ConnectionEstablished delegate is invoked. /// </summary> /// <param name="hostname">The server address, excluding the port.</param> /// <param name="nickname">The nickname to use for the player connecting.</param> /// <param name="connectionEstablished">The callback for when a connection is established.</param> /// <param name="connectionFailed">The callback for when a connection has failed.</param> internal SpaceWarsClient(string hostname, string nickname, ConnectionEstablished connectionEstablished, ConnectionFailed connectionFailed) { PlayerNickname = nickname; _connectionEstablishedCallback = connectionEstablished; _connectionFailedCallback = connectionFailed; Connect(hostname, nickname); }
public void Open(string portName, int baudRate) { _port.PortName = portName; _port.BaudRate = baudRate; _port.Open(); if (_port.IsOpen) { ConnectionEstablished?.Invoke(this); } }
public void StartListeningForConnections() { _listener.Start(); while (true) { TcpClient client = _listener.AcceptTcpClient(); ConnectionEstablished?.Invoke(this, client); } }
protected void Init(IPEndPoint remoteAddress) { _sendCommandQueue = new ConcurrentQueue <INetworkCommandAsync>(); _sendQueue = new ConcurrentQueue <FramePacket>(); _prioritySendQueue = new ConcurrentQueue <FramePacket>(); _activeRequests = new ConcurrentDictionary <INetworkCommandAsync, int>(); _activeFrameReceives = new Dictionary <ReaderType, FramePacket>(); ConnectionEstablished?.Invoke(this, remoteAddress); }
/// <summary> /// Called when a remote peer is connecting to the local peer. /// </summary> /// <param name="stream"> /// The stream to the remote peer. /// </param> /// <param name="local"> /// The local peer's address. /// </param> /// <param name="remote"> /// The remote peer's address. /// </param> /// <remarks> /// Establishes the protocols of the connection. /// </remarks> async void OnRemoteConnect(Stream stream, MultiAddress local, MultiAddress remote) { log.Debug("Got remote connection"); log.Debug("local " + local); log.Debug("remote " + remote); // TODO: Check the policies var connection = new PeerConnection { IsIncoming = true, LocalPeer = LocalPeer, LocalAddress = local, LocalPeerKey = LocalPeerKey, RemoteAddress = remote, Stream = stream }; // Mount the protocols. MountProtocols(connection); // Start the handshake // TODO: Isn't connection cancel token required. connection.ReadMessages(default(CancellationToken)); // Wait for security to be established. await connection.SecurityEstablished.Task; // TODO: Maybe connection.LocalPeerKey = null; // Wait for the handshake to complete. var muxer = await connection.MuxerEstablished.Task; // Need details on the remote peer. Identify1 identify = null; lock (protocols) { identify = protocols.OfType <Identify1>().First(); } connection.RemotePeer = await identify.GetRemotePeer(connection, default(CancellationToken)); connection.RemotePeer = RegisterPeer(connection.RemotePeer); connection.RemoteAddress = new MultiAddress($"{remote}/ipfs/{connection.RemotePeer.Id}"); connection.RemotePeer.ConnectedAddress = connection.RemoteAddress; var actual = Manager.Add(connection); if (actual == connection) { ConnectionEstablished?.Invoke(this, connection); } }
public void Open(string portName, int baudRate) { if (IsOpen) { throw new InvalidOperationException(); } else { _selectedInterface = _interfaces.SingleOrDefault(p => p.PortNames.Contains(portName)) ?? _selectedInterface; _selectedInterface.Open(portName, baudRate); ConnectionEstablished?.Invoke(this); } }
void proc() { while (true) { var clientConnection = server.Accept(); ConnectionEstablished?.Invoke(clientConnection, null); var context = new TcpContext(clientConnection) { server = this }; context.DataArrived += Context_DataArrived; var ip = (IPEndPoint)clientConnection.RemoteEndPoint; connection[ip.Address] = clientConnection; } }
/// <summary> /// On connection established event /// </summary> /// <param name="end">client address</param> protected virtual void OnConnectionEstablished(IPEndPoint end) { try { ConnectionEstablished?.Invoke(this, new ConnectionEventArgs() { Address = end.ToString(), ConnectionTime = DateTime.Now }); } catch { throw; } }
/// <summary> /// Attempts to connect to the server via a provided hostname. /// Saves the callback function in a socket state object for use when data arrives. /// </summary> /// <param name="hostName">The address to connect to.</param> /// <param name="port">The port to connect to.</param> /// <param name="established">The callback for when a connection has been established.</param> /// <param name="failed">The callback for when a connection has failed.</param> public static void ConnectToServer(string hostName, ConnectionEstablished established, ConnectionFailed failed) { // Create a SocketState. var socket = new Socket(SocketType.Stream, ProtocolType.Tcp); var socketState = new SocketState(socket, established, failed); // Attempt connection to the address on the default port. try { socket.BeginConnect(hostName, DEFAULT_PORT, ConnectedToServer, socketState); } catch (Exception e) { socketState.ConnectionFailed(e.Message); } }
private async Task SendConnectionConfirmationAsync(IClient meseClient, IEnumerable <IClient> others) { var connectionEstablished = new ConnectionEstablished { Me = meseClient.User, Others = others.Select(i => i.User).ToArray() }; var messageProtocol = new MessageProtocol { Header = MessageType.ClientConnectedSelf, Data = connectionEstablished }; await MessageCommunicator.WriteAsync(meseClient.TcpClient, messageProtocol); }
/// <summary> /// (re)establish the connection to the specified ip /// </summary> /// <returns></returns> public void Connect() { Task.Run(() => { Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us"); Debug.WriteLine($"Trying to connect to {ip}"); client = new TcpClient(); try { client.Connect(ip, 8888); Debug.WriteLine("Connection successfull"); stream = client.GetStream(); ConnectionEstablished?.Invoke(this, EventArgs.Empty); } catch (SocketException e) { ConnectFailed?.Invoke(this, EventArgs.Empty); Debug.WriteLine($"Couldn't connect because of {e}"); } }); }
public SerialPortRUSConnectionInterface(IInterface port) { _port = port; _port.ConnectionEstablished += _base_ConnectionEstablished; _port.ConnectionClosed += _base_ConnectionClosed; void _base_ConnectionClosed(object sender, EventArgs e) { ConnectionClosed?.Invoke(sender, e); } void _base_ConnectionEstablished(object sender, EventArgs e) { ConnectionEstablished?.Invoke(sender, e); } }
public void Open(string portName, int baudRate) { if (IsOpen) { Close(); } var status = getDevice(out _openedDevice); status = status == FT_STATUS.FT_OK ? _ftdi.OpenByLocation(_openedDevice.LocId) : status; status = status == FT_STATUS.FT_OK ? _ftdi.SetBaudRate(baudRate.ToUInt32()) : status; status = status == FT_STATUS.FT_OK ? _ftdi.SetDataCharacteristics(8, 0, 0) : status; status = status == FT_STATUS.FT_OK ? _ftdi.SetFlowControl(0x0000, 0x00, 0x00) : status; status = status == FT_STATUS.FT_OK ? _ftdi.SetLatency(1) : status; status = status == FT_STATUS.FT_OK ? _ftdi.SetUSBParameters(32768, 0) : status; status = status == FT_STATUS.FT_OK ? _ftdi.SetTimeouts(1, 1) : status; if (status == FT_STATUS.FT_OK) { PortName = portName; ConnectionEstablished?.Invoke(this); } else { Logger.LogError($"Не удалось открыть порт {portName}", $"-MSG, статус: {status}"); _openedDevice = null; Close(); } FT_STATUS getDevice(out FT_DEVICE_INFO_NODE device) { var index = portName .SkipWhile(char.IsLetter) .Aggregate() .ParseToUInt32Invariant(); device = getAllDevices().ElementAtOrDefault((int)index); return(device == null ? FT_STATUS.FT_DEVICE_NOT_FOUND : FT_STATUS.FT_OK); } }
private void OnStateChangedEvent(UnityMCPeerID arg1, UnityMCSessionState arg2) { // todo: handle multi-user Debug.Log("State: " + arg2.ToString() + " with user: "******"Unexpected state: " + arg2); break; } }
/// <summary> /// Starts an internal loop that will continually accept connections from clients until stopped via the returned TcpState. /// </summary> /// <param name="port">The port to listen on.</param> /// <param name="established">The callback for when a connection to a client has been established.</param> /// <param name="failed">The callback for when a connection to a client has failed.</param> /// <returns>A TcpState, which can be used to stop accepting connections from clients.</returns> public static TcpState AwaitClientConnections(int port, ConnectionEstablished established, ConnectionFailed failed) { var listener = new TcpListener(IPAddress.Any, port); var tcpState = new TcpState(listener, established, failed); // Start accepting the socket from the client. try { listener.Start(); listener.BeginAcceptSocket(AcceptClientSocket, tcpState); } catch (Exception e) { failed(e.Message); } return(tcpState); }
/// <summary> /// Initialize a <see cref="DurableConnection"/> object /// </summary> /// <param name="retryPolicy"></param> /// <param name="watcher"></param> /// <param name="connectionFactory"></param> public DurableConnection(IRetryPolicy retryPolicy, IRabbitWatcher watcher, ConnectionFactory connectionFactory) : this(retryPolicy, watcher) { if (connectionFactory == null) { throw new ArgumentNullException(nameof(connectionFactory)); } _connectionFactory = ManagedConnectionFactory.CreateFromConnectionFactory(connectionFactory); ConnectionEstablished handler = (endpoint, virtualHost) => { if (_connectionFactory.Endpoint + _connectionFactory.VirtualHost == endpoint + virtualHost) { //NOTE: Fire connected event whenever a new connection to 1 of the servers in the cluster is made FireConnectedEvent(); } }; ManagedConnectionFactory.ConnectionEstablished += handler; _unsubscribeEvents = () => { ManagedConnectionFactory.ConnectionEstablished -= handler; }; }
public async Task Handle(ConnectionEstablished notification, CancellationToken cancellationToken) { if (!HistorianConfiguration.Npgsql.Enable) { return; } await Mediator.Publish(new SubscribeRequest() { Qos = MeasurementsConfiguration.Qos, Topic = $"{Prefix}/+", }, cancellationToken); foreach (var topic in HistorianConfiguration.Npgsql.GenericJson.Items.SelectMany(t => t.Topics)) { await Mediator.Publish(new SubscribeRequest() { Qos = MeasurementsConfiguration.Qos, Topic = topic, }, cancellationToken); } }
/// <summary> /// Accept new connections. /// </summary> /// <param name="asyncResult"></param> private void AcceptCallback(IAsyncResult asyncResult) { //Stops accepting new connections when listenSocket is shutdown if (State == ServerState.Down) { return; } //Accept the new connection Socket acceptedSocket = listenSocket.EndAccept(asyncResult); byte clientId = AddClient(acceptedSocket); //Send the id to the client acceptedSocket.Send(Commands.SetPlayerId(clientId)); //Start receiving data from the client ConnectionEstablished?.Invoke(); BeginReceiving(acceptedSocket); //Start accepting the next connection BeginAccepting(); }
public bool Connect() { CloseConnection(); TCPClient = new TcpClient(); try { TCPClient.Connect(IPAddress, Port); DataStream = TCPClient.GetStream(); Log($"connect successully!!"); Init(); Log($"invoking ConnectionEstablished"); ConnectionEstablished?.Invoke(); Log($"invoking ConnectionEstablished, done"); return(true); } catch (Exception e) { Log($"exception thrown when connecting {e.Message}"); TCPClient.Dispose(); return(false); } }
public void Start() { if (socket != null && ClientOptions != null) { if (!Running) { Running = true; ConnectionEstablished?.Invoke(this); DOSWatch = Stopwatch.StartNew(); pingWatch = Stopwatch.StartNew(); BeginReceive(); } else { throw new InvalidOperationException("Client is already running"); } } else { throw new InvalidOperationException("Socket or SocketOptions can't be null"); } }
public DurableConnection(IRetryPolicy retryPolicy, IRabbitWatcher watcher, ConnectionFactory connectionFactory) : this(retryPolicy, watcher) { if (connectionFactory == null) { throw new ArgumentNullException(nameof(connectionFactory)); } _connectionFactory = ManagedConnectionFactory.CreateFromConnectionFactory(connectionFactory); ConnectionEstablished hander = (endpoint, virtualHost) => { if (_connectionFactory.Endpoint + _connectionFactory.VirtualHost == endpoint + virtualHost) { //NOTE: 当集群中的服务器的一个新连接被建立时,触发事件连接事件 FireConnectedEvent(); } }; ManagedConnectionFactory.ConnectionEstablished += hander; _unsubscribeEvents = () => { ManagedConnectionFactory.ConnectionEstablished -= hander; }; }
private void runClient(object obj) { ThreadClientParam param = obj as ThreadClientParam; string role = "Client"; NetworkClient n = new NetworkClient(this.ipAddress, this.port); ConnectionEstablished threadStoppedDel = new ConnectionEstablished(threadStopped); int i = 1; AddMessageDelegate addMessage = new AddMessageDelegate(AddMessage); Dispatcher.Invoke(addMessage, "Connecting to: " + this.ipAddress + ":" + this.port); bool startGameMessageReceived = false; bool wasGameStarted = false; int maxNumberOfConnectionAttempts = 3; try { while (i <= maxNumberOfConnectionAttempts && endTheThread != 1) { startGameMessageReceived = false; DebuggerIX.WriteLine(DebuggerTag.Net, role, "Initialization # " + i + " invoked"); Dispatcher.Invoke(addMessage, "Attempt to receive connection #" + i); try { n.InitializeConnection(); } catch (InvalidStateException e) { DebuggerIX.WriteLine(DebuggerTag.Net, role, "InvalidState: " + e.Message); Dispatcher.Invoke(addMessage, "Error:" + e.Message); continue; } catch (TimeoutException e) { DebuggerIX.WriteLine(DebuggerTag.Net, role, "TimeOut: " + e.Message); Dispatcher.Invoke(addMessage, "Timeout for attempt #" + i); continue; } DebuggerIX.WriteLine(DebuggerTag.Net, role, "Initialization = " + n.IsInitialized); if (n.IsInitialized == false) { Dispatcher.Invoke(addMessage, n.ErrorMessage); } else { DebuggerIX.WriteLine(DebuggerTag.Net, role, "Sending 'Autentization'"); n.SendAsync(NetworkMessageType.Authentication, param.Authentication); try { n.AllSentHandle.WaitOne(3000); // wait until all is sent } catch (TimeoutException) { DebuggerIX.WriteLine(DebuggerTag.Net, role, "Timeout"); Dispatcher.Invoke(addMessage, "Timeout"); continue; } DebuggerIX.WriteLine(DebuggerTag.Net, role, "'Autentization' sent"); Dispatcher.Invoke(addMessage, "Handshake sent"); bool disconnect = false; Authentication auth = null; int noneMessageNo = 0; while (startGameMessageReceived == false && disconnect == false && n.IsInitialized == true) { DebuggerIX.WriteLine(DebuggerTag.Net, role, "Start async receiving"); n.ReceiveAsync(); DebuggerIX.WriteLine(DebuggerTag.Net, role, "Waiting for a message to be received"); try { n.ReceivedMessageHandle.WaitOne(2500); } catch (TimeoutException) { DebuggerIX.WriteLine(DebuggerTag.Net, role, "Timeout"); Dispatcher.Invoke(addMessage, "Timeout"); break; } NetworkMessageType messageType = n.GetReceivedMessageType(); DebuggerIX.WriteLine(DebuggerTag.Net, role, "Received message: " + messageType); object message = null; if (messageType != NetworkMessageType.None) { noneMessageNo = 0; message = n.GetReceivedMessageFromQueue(); } if (messageType == NetworkMessageType.Authentication) { auth = (Authentication)message; DebuggerIX.WriteLine(DebuggerTag.Net, role, string.Format("'Autentization' message details: {0}, {1}", auth.Name, auth.IP)); Dispatcher.Invoke(addMessage, "Autentization message received"); } else if (messageType == NetworkMessageType.DisconnectRequest) { DisconnectRequest dr = (DisconnectRequest)message; DebuggerIX.WriteLine(DebuggerTag.Net, role, "'DisconnectRequest' was sent by the other side in: " + dr.DateTime); DebuggerIX.WriteLine(DebuggerTag.Net, role, "Sending 'DisconnectRequestConfirmation' message"); n.SendAsync(NetworkMessageType.DisconnectRequestConfirmation); n.AllSentHandle.WaitOne(); DebuggerIX.WriteLine(DebuggerTag.Net, role, "'DisconnectRequestConfirmation' sent"); disconnect = true; Dispatcher.Invoke(addMessage, "Send request to end handshake"); } else if (messageType == NetworkMessageType.StartGame) { startGameMessageReceived = true; } else if (messageType == NetworkMessageType.None) { noneMessageNo++; if (noneMessageNo > 2) { Dispatcher.Invoke(addMessage, "No message was received in three attempts in a row. Giving up."); break; } else { Dispatcher.Invoke(addMessage, "No message was received."); } } else { Dispatcher.Invoke(addMessage, "Warning: Unknown message received."); } } if (n.IsInitialized == false) { Dispatcher.Invoke(addMessage, "Connection lost."); DebuggerIX.WriteLine(DebuggerTag.Net, role, "Connection lost."); } if (disconnect) { n.CloseConnection(); Dispatcher.Invoke(addMessage, "End of initial handshake"); DebuggerIX.WriteLine(DebuggerTag.Net, role, "Connection closed."); } if (startGameMessageReceived && auth != null) { wasGameStarted = true; Dispatcher.Invoke(addMessage, "Game is about to start."); Dispatcher.Invoke(new EstablishConnectionDelegate(establishConnection), new object[] { n, auth }); break; // from outer while cyclus } } i++; } if (wasGameStarted == false) { DebuggerIX.WriteLine(DebuggerTag.Net, role, "All attempts tried. Click 'Again' to begin again."); Dispatcher.Invoke(addMessage, "All attempts tried. Click 'Again' to begin again."); } else { Dispatcher.BeginInvoke(threadStoppedDel, new object[] { wasGameStarted }); } } catch (ThreadInterruptedException e) { n.CloseConnection(); DebuggerIX.WriteLine(DebuggerTag.Net, role, "Thread interrupted. Message: " + e.Message); Dispatcher.Invoke(addMessage, "Connection attempts aborted by user request."); } finally { if (wasGameStarted == false) { n.CloseConnection(); Dispatcher.Invoke(addMessage, "Network connection searching was disabled."); } } DebuggerIX.WriteLine(DebuggerTag.Net, role, "Finished"); }
void _base_ConnectionEstablished(object sender, EventArgs e) { ConnectionEstablished?.Invoke(this, e); }
/// <summary> /// Called when a remote peer is connecting to the local peer. /// </summary> /// <param name="stream"> /// The stream to the remote peer. /// </param> /// <param name="local"> /// The local peer's address. /// </param> /// <param name="remote"> /// The remote peer's address. /// </param> /// <remarks> /// Establishes the protocols of the connection. Any exception is simply /// logged as warning. /// </remarks> async void OnRemoteConnect(Stream stream, MultiAddress local, MultiAddress remote) { // If the remote is already trying to establish a connection, then we // can just refuse this one. if (!pendingRemoteConnections.TryAdd(remote, null)) { log.Debug($"Duplicate remote connection from {remote}"); stream.Dispose(); return; } try { log.Debug($"{LocalPeer.Id} got remote connection"); log.Debug("local " + local); log.Debug("remote " + remote); // TODO: Check the policies var connection = new PeerConnection { IsIncoming = true, LocalPeer = LocalPeer, LocalAddress = local, LocalPeerKey = LocalPeerKey, RemoteAddress = remote, Stream = stream }; // Are we communicating to a private network? if (NetworkProtector != null) { connection.Stream = await NetworkProtector.ProtectAsync(connection).ConfigureAwait(false); } // Mount the protocols. MountProtocols(connection); // Start the handshake // TODO: Isn't connection cancel token required. connection.ReadMessages(default(CancellationToken)); // Wait for security to be established. await connection.SecurityEstablished.Task.ConfigureAwait(false); // TODO: Maybe connection.LocalPeerKey = null; // Wait for the handshake to complete. var muxer = await connection.MuxerEstablished.Task; // Need details on the remote peer. Identify1 identify = null; lock (protocols) { identify = protocols.OfType <Identify1>().First(); } connection.RemotePeer = await identify.GetRemotePeer(connection, default(CancellationToken)).ConfigureAwait(false); connection.RemotePeer = RegisterPeer(connection.RemotePeer); connection.RemoteAddress = new MultiAddress($"{remote}/ipfs/{connection.RemotePeer.Id}"); var actual = Manager.Add(connection); if (actual == connection) { ConnectionEstablished?.Invoke(this, connection); } } catch (Exception e) { log.Warn("Remote connect failed", e); try { stream.Dispose(); } catch (Exception) { // eat it. } } finally { pendingRemoteConnections.TryRemove(remote, out object _); } }
private void runServer(object obj) { ThreadServerParam param = obj as ThreadServerParam; string role = "Server"; NetworkServer n = new NetworkServer(this.ipAddress, this.port); int maxPlayersToWaitFor = MAX_PLAYERS_TO_WAIT_FOR; int i = 1; AddAutentizationDelegate addPlayer = new AddAutentizationDelegate(AddPlayer); AddMessageDelegate addMessage = new AddMessageDelegate(AddMessage); ConnectionEstablished threadStoppedDel = new ConnectionEstablished(threadStopped); if (this.ipAddress == "Automatic") { Dispatcher.Invoke(addMessage, "Listening on port: " + this.port); } else { Dispatcher.Invoke(addMessage, "Listening on: " + this.ipAddress + ":" + this.port); } bool isAutenticated = false; try { while (i <= maxPlayersToWaitFor && endTheThread != 1) { isAutenticated = false; DebuggerIX.WriteLine(DebuggerTag.Net, role, "Initialization # " + i + " invoked"); Dispatcher.Invoke(addMessage, "Attempt to receive connection #" + i); try { n.InitializeConnection(); } catch (InvalidStateException e) { DebuggerIX.WriteLine(DebuggerTag.Net, role, "InvalidState: " + e.Message); Dispatcher.Invoke(addMessage, "Error:" + e.Message); n.CloseConnection(); } catch (TimeoutException e) { DebuggerIX.WriteLine(DebuggerTag.Net, role, "TimeOut: " + e.Message); Dispatcher.Invoke(addMessage, "Timeout for attempt #" + i); n.CloseConnection(); } DebuggerIX.WriteLine(DebuggerTag.Net, role, "Initialization = " + n.IsInitialized); if (n.IsInitialized == true) { DebuggerIX.WriteLine(DebuggerTag.Net, role, "Sending 'Autentization'"); n.SendAsync(NetworkMessageType.Authentication, param.Authentication); n.AllSentHandle.WaitOne(); // wait until all is sent DebuggerIX.WriteLine(DebuggerTag.Net, role, "'Autentization' sent"); Dispatcher.Invoke(addMessage, "Handshake sent"); bool disconnect = false; Authentication auth = null; while (isAutenticated == false && disconnect == false) { DebuggerIX.WriteLine(DebuggerTag.Net, role, "Start async receiving"); n.ReceiveAsync(); DebuggerIX.WriteLine(DebuggerTag.Net, role, "Waiting for a message to be received"); n.ReceivedMessageHandle.WaitOne(5000); NetworkMessageType messageType = n.GetReceivedMessageType(); DebuggerIX.WriteLine(DebuggerTag.Net, role, "Received message: " + messageType); if (messageType == NetworkMessageType.Authentication) { auth = (Authentication)n.GetReceivedMessageFromQueue(); DebuggerIX.WriteLine(DebuggerTag.Net, role, string.Format("'Autentization' message details: {0}, {1}", auth.Name, auth.IP)); Dispatcher.Invoke(addPlayer, auth); Dispatcher.Invoke(addMessage, "Autentization message received"); if (param.AutomaticFirstConnect) { Dispatcher.Invoke(addMessage, "Accepting game opponent."); isAutenticated = true; DebuggerIX.WriteLine(DebuggerTag.Net, role, "Sending 'StartGame' message"); n.SendAsync(NetworkMessageType.StartGame); n.AllSentHandle.WaitOne(); DebuggerIX.WriteLine(DebuggerTag.Net, role, "'StartGame' sent"); } } else if (messageType == NetworkMessageType.DisconnectRequest) { DisconnectRequest dr = (DisconnectRequest)n.GetReceivedMessageFromQueue(); DebuggerIX.WriteLine(DebuggerTag.Net, role, "'DisconnectRequest' was sent by the other side in: " + dr.DateTime); DebuggerIX.WriteLine(DebuggerTag.Net, role, "Sending 'DisconnectRequestConfirmation' message"); n.SendAsync(NetworkMessageType.DisconnectRequestConfirmation); n.AllSentHandle.WaitOne(); DebuggerIX.WriteLine(DebuggerTag.Net, role, "'DisconnectRequestConfirmation' sent"); disconnect = true; Dispatcher.Invoke(addMessage, "Send request to end handshake"); } } if (disconnect) { n.CloseConnection(); Dispatcher.Invoke(addMessage, "End of initial handshake"); DebuggerIX.WriteLine(DebuggerTag.Net, role, "Connection closed."); } if (isAutenticated) { Dispatcher.Invoke(new EstablishConnectionDelegate(establishConnection), new object[] { n, auth}); break; // from outer while cyclus } } i++; } if (isAutenticated == false) { Dispatcher.Invoke(addMessage, "All attempts tried. Click 'listen' to begin again."); } } catch (ThreadInterruptedException) { DebuggerIX.WriteLine(DebuggerTag.Net, role, "Thread interrupted."); n.CloseConnection(); } finally { if (isAutenticated == false) { n.CloseConnection(); } Dispatcher.Invoke(addMessage, "Network connection searching was disabled."); DebuggerIX.WriteLine(DebuggerTag.Net, role, "Finished"); Dispatcher.Invoke(threadStoppedDel, new object[] {isAutenticated}); } }