コード例 #1
0
        /// <summary>
        /// Disconnects the user from the server.
        /// </summary>
        /// <returns>True if the user is disconnected from the server.</returns>
        public async Task <bool> SignOut()
        {
            if (_state == State.NOT_CONNECTED || _state == State.SIGNING_OUT)
            {
                return(true);
            }

            if (_hangingGetSocket != null)
            {
                _hangingGetSocket.Dispose();
                _hangingGetSocket = null;
            }

            _state = State.SIGNING_OUT;

            if (_myId != -1)
            {
                await ControlSocketRequestAsync(string.Format(
                                                    "GET /sign_out?peer_id={0} HTTP/1.0\r\nHost: {1}\r\n\r\n",
                                                    _myId,
                                                    _server))
                .ConfigureAwait(false);
            }
            else
            {
                // Can occur if the app is closed before we finish connecting
                return(true);
            }

            _myId  = -1;
            _state = State.NOT_CONNECTED;
            return(true);
        }
コード例 #2
0
        /// <summary>
        /// Called when a connection attempt complete, successfully or not.
        /// !!! NOTE These do not arrive on the main Unity Thread. Most Unity operations will throw in the callback !!!
        /// </summary>
        /// <param name="asyncInfo">Data about the async operation.</param>
        /// <param name="status">The status of the operation.</param>
        public void NetworkConnectedHandler(IAsyncAction asyncInfo, AsyncStatus status)
        {
            // Status completed is successful.
            if (status == AsyncStatus.Completed)
            {
                DataWriter networkDataWriter;

                // Since we are connected, we can send the data we set aside when establishing the connection.
                using (networkDataWriter = new DataWriter(networkConnection.OutputStream))
                {
                    // Write how much data we are sending.
                    networkDataWriter.WriteInt32(nextDataBufferToSend.Length);

                    // Then write the data.
                    networkDataWriter.WriteBytes(nextDataBufferToSend);

                    // Again, this is an async operation, so we'll set a callback.
                    DataWriterStoreOperation dswo = networkDataWriter.StoreAsync();
                    dswo.Completed = new AsyncOperationCompletedHandler <uint>(DataSentHandler);
                }
            }
            else
            {
                Debug.Log("Failed to establish connection. Error Code: " + asyncInfo.ErrorCode);
                // In the failure case we'll requeue the data and wait before trying again.
                networkConnection.Dispose();

                // Didn't send, so requeue the data.
                dataQueue.Enqueue(nextDataBufferToSend);

                // And set the defer time so the update loop can do the 'Unity things'
                // on the main Unity thread.
                deferTime = timeToDeferFailedConnections;
            }
        }
コード例 #3
0
        protected override void Abort(int traceEventType, string timeoutErrorString, TransferOperation transferOperation)
        {
            lock (ThisLock)
            {
                if (_closeState == CloseState.Closed)
                {
                    return;
                }

                _timeoutErrorString            = timeoutErrorString;
                _timeoutErrorTransferOperation = transferOperation;
                _aborted    = true;
                _closeState = CloseState.Closed;

                if (_asyncReadPending)
                {
                    CancelReceiveTimer();
                }
                else
                {
                    this.ReturnReadBuffer();
                }

                if (_asyncWritePending)
                {
                    CancelSendTimer();
                }
            }

            _socket.Dispose();
        }
コード例 #4
0
        // Only included if HoloLens
#if !UNITY_EDITOR && UNITY_WSA_10_0
        /// <summary>
        /// Called when the async action is completed (establishing a connection within SendMesh(string networkConfig))
        /// If connection is successful, write the Room Mesh data from the Database to the network connection
        /// If connection is unsuccessful, dispose of the client (StreamSocket)
        /// </summary>
        /// <param name="asyncInfo">Information about the async action</param>
        /// <param name="status">The current status of the async action</param>
        public void NetworkConnectedHandler(IAsyncAction asyncInfo, AsyncStatus status)
        {
            //Debug.Log("YOU CONNECTED TO: " + networkConnection.Information.RemoteAddress.ToString());

            // Status completed is successful.
            if (status == AsyncStatus.Completed)
            {
                Debug.Log("PREPARING TO WRITE DATA...");

                DataWriter networkDataWriter;

                // Since we are connected, we can send the data we set aside when establishing the connection.
                using (networkDataWriter = new DataWriter(holoClient.OutputStream)) {
                    Debug.Log("PREPARING TO WRITE DATA");
                    // Then write the data.
//                    networkDataWriter.WriteBytes(Database.GetMeshAsBytes());

                    // Again, this is an async operation, so we'll set a callback.
                    DataWriterStoreOperation dswo = networkDataWriter.StoreAsync();
                    dswo.Completed = new AsyncOperationCompletedHandler <uint>(DataSentHandler);
                }
            }
            else
            {
                Debug.LogWarning("Failed to establish connection. Error Code: " + asyncInfo.ErrorCode);
                // In the failure case we'll requeue the data and wait before trying again.
                holoClient.Dispose();
            }
        }
コード例 #5
0
ファイル: TCPClient.cs プロジェクト: ndomanovskiy/vUnivere
        public async Task connectWithServer(string hostName, string port)
        {
            if (connected)
            {
                _status += "Already connected";
                return;
            }

            try
            {
                _status = "Trying to connect ...";

                serverHost = new HostName(hostName);
                await clientSocket.ConnectAsync(serverHost, port);

                connected = true;
                _status   = "Connection established";
            }
            catch (Exception exception)
            {
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                _status += "Connect failed with error: " + exception.Message;

                clientSocket.Dispose();
                clientSocket = null;
            }
        }
コード例 #6
0
        /// <summary>
        /// Connects this instance.
        /// </summary>
        /// <returns>Task.</returns>
        public async Task Connect()
        {
            if (_socket != null)
            {
                _socket.Dispose();
            }

            try
            {
                _socket = new StreamSocket();

                await _socket.ConnectAsync(_device.HostName, _device.ServiceName);

                //return true;
            }
            catch             //(Exception ex)
            {
                if (_socket != null)
                {
                    _socket.Dispose();
                    _socket = null;
                }

                throw;
            }
        }
コード例 #7
0
            public void Close()
            {
                _streamWatcher.DataAvailible -= StreamWatcherOnDataAvailible;
                _streamWatcher.Stop();
                _streamWatcher = null;

                _socket.Dispose();
            }
コード例 #8
0
 private void DisconnectSender()
 {
     if (sender != null)
     {
         sender.Dispose();
         sender = null;
     }
 }
コード例 #9
0
    public void NetworkConnectedHandler(IAsyncAction asyncInfo, AsyncStatus status)
    {
        DataWriter networkDataWriter;

        // Status completed is successful.
        if (status == AsyncStatus.Completed)
        {
            // Since we are connected, we can send the data we set aside when establishing the connection.
            using (networkDataWriter = new DataWriter(socket2.OutputStream))
            {
                Debug.Log("Sending " + stringToSend + " to " + strhostname + " at port " + strport);
                //networkDataWriter.WriteUInt32(networkDataWriter.MeasureString(stringToSend));
                //networkDataWriter.WriteString(stringToSend);
                if (stringToSend == "1")
                {
                    networkDataWriter.WriteByte(1);
                }
                else if (stringToSend == "2")
                {
                    networkDataWriter.WriteByte(2);
                }
                else if (stringToSend == "3")
                {
                    networkDataWriter.WriteByte(3);
                }
                else if (stringToSend == "4")
                {
                    networkDataWriter.WriteByte(4);
                }
                else if (stringToSend == "5")
                {
                    networkDataWriter.WriteByte(5);
                }

                //networkDataWriter.WriteByte(valuetosend);

                // Again, this is an async operation, so we'll set a callback.
                try
                {
                    DataWriterStoreOperation dswo = networkDataWriter.StoreAsync();
                    dswo.Completed = new AsyncOperationCompletedHandler <uint>(DataSentHandler);
                    Debug.Log("NetworkConnectedHandler ::Sending");
                }
                catch (Exception exception)
                {
                    Debug.Log("Store async exception");
                }
            }
        }
        else
        {
            Debug.Log("Failed to establish connection. Error Code: " + asyncInfo.ErrorCode);
            // In the failure case we'll requeue the data and wait before trying again.
            socket2.Dispose();
        }
    }
コード例 #10
0
 /// <inheritdoc />
 public void Stop()
 {
     _streamTcs?.TrySetCanceled();
     _streamTcs = null;
     _tokenRegistration.Dispose();
     _listener.ConnectionReceived -= OnConnectionReceived;
     _listener.Dispose();
     _socket?.Dispose();
     _socket = null;
 }
コード例 #11
0
        async private void ConnectDevice_Click(object sender, RoutedEventArgs e)
        {
            //Revision: No need to requery for Device Information as we alraedy have it:
            DeviceInformation DeviceInfo; // = await DeviceInformation.CreateFromIdAsync(this.TxtBlock_SelectedID.Text);
            PairedDeviceInfo  pairedDevice = (PairedDeviceInfo)ConnectDevices.SelectedItem;

            DeviceInfo = pairedDevice.DeviceInfo;

            bool success = true;

            try
            {
                _service = await RfcommDeviceService.FromIdAsync(DeviceInfo.Id);

                if (_socket != null)
                {
                    // Disposing the socket with close it and release all resources associated with the socket
                    _socket.Dispose();
                }

                _socket = new StreamSocket();
                try
                {
                    // Note: If either parameter is null or empty, the call will throw an exception
                    await _socket.ConnectAsync(_service.ConnectionHostName, _service.ConnectionServiceName);
                }
                catch (Exception ex)
                {
                    success = false;
                    System.Diagnostics.Debug.WriteLine("Connect:" + ex.Message);
                }
                // If the connection was successful, the RemoteAddress field will be populated
                if (success)
                {
                    this.buttonDisconnect.IsEnabled   = true;
                    this.buttonSend.IsEnabled         = true;
                    this.buttonStartRecv.IsEnabled    = true;
                    this.buttonStartProcess.IsEnabled = true;
                    this.buttonStopRecv.IsEnabled     = false;
                    this.StartStopReceive.IsEnabled   = true;

                    string msg = String.Format("Connected to {0}!", _socket.Information.RemoteAddress.DisplayName);
                    //MessageDialog md = new MessageDialog(msg, Title);
                    System.Diagnostics.Debug.WriteLine(msg);
                    //await md.ShowAsync();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Overall Connect: " + ex.Message);
                _socket.Dispose();
                _socket = null;
            }
        }
コード例 #12
0
 public override void Close()
 {
     if (!IsClosed)
     {
         base.Close();
         try { iS.Dispose(); } catch (Exception) { }
         try { oS.Dispose(); } catch (Exception) { }
         try { streamSocket.Dispose(); } catch (Exception) { }
         Log(Level.Info, "Closed.");
     }
 }
コード例 #13
0
ファイル: FtpClient.cs プロジェクト: jbubicz/uwp_tutorials
        internal async Task <IBuffer> ReadAndCloseAsync(uint dataLength)
        {
            IBuffer buffer = new Windows.Storage.Streams.Buffer(dataLength);

            await dataStreamSocket.InputStream.ReadAsync(buffer, dataLength, InputStreamOptions.None);

            dataStreamSocket.Dispose();
            dataStreamSocket = null;

            return(buffer);
        }
コード例 #14
0
ファイル: NetworkConnection.cs プロジェクト: mikeries/Empire
        private async void TCPConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            StreamSocket socket = args.Socket;
            DataReader   reader = new DataReader(socket.InputStream);

            try
            {
                while (true)
                {
                    uint MessageSize = await reader.LoadAsync(sizeof(uint));

                    if (MessageSize != sizeof(uint))
                    {
                        // socket was closed
                        reader.Dispose();
                        socket.Dispose();
                        return;
                    }

                    uint   dataLength = reader.ReadUInt32();
                    byte[] data       = new byte[dataLength];

                    uint actualLength = await reader.LoadAsync(dataLength);

                    if (dataLength != actualLength)
                    {
                        // socket was closed
                        reader.Dispose();
                        socket.Dispose();
                        return;
                    }
                    reader.ReadBytes(data);

                    // TODO: Most packets sent won't require a response and won't need to be awaited, which blocks the port
                    // consider using a different port with a different handler for those that do.
                    // For those that don't require a response, simply invoke the callback function and move on.
                    if (_tcpCallback != null)
                    {
                        byte[] response = await _tcpCallback(socket, data);
                        await sendTCPData(socket, response);
                    }
                }
            }
            catch (Exception e)
            {
                if (SocketError.GetStatus(e.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }
            }
            socket.Dispose();
            reader.Dispose();
        }
コード例 #15
0
        public void Disconnect()
        {
            if (_controlChannelSocket != null)
            {
                _controlChannelSocket.Dispose();
                _controlChannelSocket = null;
            }

            if (_dataChannelSocket != null)
            {
                _dataChannelSocket.Dispose();
                _dataChannelSocket = null;
            }
        }
コード例 #16
0
 private async Task Stop()
 {
     if (socket != null)
     {
         socket.Dispose();
         socket = null;
     }
     deviceList.Enabled    = true;
     refreshButton.Enabled = true;
     connectButton.Enabled = false;
     closeButton.Enabled   = false;
     sendButton.Enabled    = false;
     await LoadDeviceList().ConfigureAwait(true);
 }
コード例 #17
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            //OutBuff = new Windows.Storage.Streams.Buffer(100);
            Button button = (Button)sender;

            if (button != null)
            {
                switch ((string)button.Content)
                {
                case "Disconnect":
                    await this._socket.CancelIOAsync();

                    _socket.Dispose();
                    _socket = null;
                    //this.textBlockBTName.Text = "";
                    //this.TxtBlock_SelectedID.Text = "";
                    this.buttonDisconnect.IsEnabled = false;
                    this.buttonSend.IsEnabled       = false;
                    this.buttonStartRecv.IsEnabled  = false;
                    this.buttonStopRecv.IsEnabled   = false;
                    break;

                //case "Send":
                //    //await _socket.OutputStream.WriteAsync(OutBuff);
                //    Send(this.textBoxSendText.Text);
                //    //  this.textBoxSendText.Text = "";
                //    break;
                //case "Clear Send":
                //    // this.textBoxRecvdText.Text = "";
                //    break;
                case "Start Recv":
                    this.buttonStartRecv.IsEnabled = false;
                    this.buttonStopRecv.IsEnabled  = true;
                    Listen();
                    break;

                case "Stop Recv":
                    this.buttonStartRecv.IsEnabled = false;
                    this.buttonStopRecv.IsEnabled  = false;
                    CancelReadTask();
                    break;

                case "Refresh":
                    InitializeRfcommDeviceService();
                    break;
                }
            }
        }
コード例 #18
0
        private async void Disconnect()
        {
            if (_rfcommProvider != null)
            {
                _rfcommProvider.StopAdvertising();
                _rfcommProvider = null;
            }

            if (_socketListener != null)
            {
                _socketListener.Dispose();
                _socketListener = null;
            }

            if (_writer != null)
            {
                _writer.DetachStream();
                _writer = null;
            }

            if (_socket != null)
            {
                _socket.Dispose();
                _socket = null;
            }
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                ListenButton.IsEnabled     = true;
                DisconnectButton.IsEnabled = false;
                ConversationListBox.Items.Clear();
            });
        }
コード例 #19
0
 public void Dispose()
 {
     _writer?.Dispose();
     _writer = null;
     _tcpSocket?.Dispose();
     _tcpSocket = null;
 }
コード例 #20
0
        /// <summary>
        /// Cleans up the socket and DataWriter and reset the UI
        /// </summary>
        /// <param name="disconnectReason"></param>
        private void Disconnect(string disconnectReason)
        {
            if (chatWriter != null)
            {
                chatWriter.DetachStream();
                chatWriter = null;
            }


            if (chatService != null)
            {
                chatService.Dispose();
                chatService = null;
            }
            lock (this)
            {
                if (chatSocket != null)
                {
                    chatSocket.Dispose();
                    chatSocket = null;
                }
            }

            rootPage.NotifyUser(disconnectReason, NotifyType.StatusMessage);
            ResetUI();
        }
コード例 #21
0
 public void ClientClose()
 {
     if (client != null)
     {
         client.Dispose();
     }
 }
コード例 #22
0
ファイル: ConnectionManager.cs プロジェクト: hugsy/CFB
        public async Task <bool> Close()
        {
            await Task.Run(() => ClientSocket.Dispose());

            _Status = BrokerConnectionStatus.Disconnected;
            return(true);
        }
コード例 #23
0
        public async Task Connect(PeerInformation peer)
        {
            StreamSocket socket = null;
            BinaryWriter writer = null;

            Disconnect();

            try
            {
                socket = new StreamSocket();

                await socket.ConnectAsync(peer.HostName, "{00001101-0000-1000-8000-00805f9b34fb}");

                writer = new BinaryWriter(socket.OutputStream.AsStreamForWrite());

                Socket = socket;
                Writer = writer;
                Peer   = peer;
            }
            catch (Exception e)
            {
                writer?.Dispose();
                writer = null;

                socket?.Dispose();
                socket = null;

                throw;
            }
        }
コード例 #24
0
        public async Task <EchoResult> CloseAsync()
        {
            if (tcpSocket != null)
            {
                await tcpDw.FlushAsync();

                tcpDw.Dispose();
                tcpSocket.Dispose();
                tcpSocket = null;
                tcpDw     = null;

                // Wait for the TcpReadTask to finish
                if (TcpReadTask != null)
                {
                    await TcpReadTask;
                }
            }
            if (udpSocket != null) //TODO: what other clients need to close their UDP sockets?
            {
                udpDw.Dispose();
                udpDw     = null;
                udpSocket = null;
            }
            return(TcpReadEchoResult); // Not really fully correct.
        }
コード例 #25
0
 private void Disconnect()
 {
     if (reader != null)
     {
         reader.DetachStream();
         reader.Dispose();
         reader = null;
     }
     if (writer != null)
     {
         writer.DetachStream();
         writer.Dispose();
         writer = null;
     }
     if (socket != null)
     {
         lock (this)
         {
             socket.Dispose();
         }
         socket = null;
     }
     BTService            = null;
     BTDevice             = null;
     DeviceInfoCollection = null;
 }
コード例 #26
0
        public override void Disconnect()
        {
            if (_writer != null)
            {
                _writer.DetachStream();
                _writer = null;
            }

            if (_deviceService != null)
            {
                _deviceService.Dispose();
                _deviceService = null;
            }

            lock (this)
            {
                if (_socket != null)
                {
                    _socket.Dispose();
                    _socket = null;
                }
            }

            ConnectCommand.Enabled = true;
        }
コード例 #27
0
        private void CloseConnection(bool continueAdvertise)
        {
            if (_dataReader != null)
            {
                _dataReader.Dispose();
                _dataReader = null;
            }

            if (_dataWriter != null)
            {
                _dataWriter.Dispose();
                _dataWriter = null;
            }

            if (_socket != null)
            {
                _socket.Dispose();
                _socket = null;
            }

            if (continueAdvertise)
            {
                // Since there is no connection, let's advertise ourselves again, so that peers can find us.
                PeerFinder.Start();
            }
            else
            {
                PeerFinder.Stop();
            }
        }
コード例 #28
0
 public void Disconnect()
 {
     Listening = false;
     if (provider != null)
     {
         if (isAdvertising)
         {
             provider.StopAdvertising();
         }
         provider = null;
     }                                                                                                      // StopAdvertising relentlessly causes a crash if not advertising.
     if (socketListener != null)
     {
         socketListener.Dispose(); socketListener = null;
     }
     if (writer != null)
     {
         writer.DetachStream(); writer.Dispose(); writer = null;
     }
     if (reader != null)
     {
         reader.DetachStream(); reader.Dispose(); reader = null;
     }
     if (socket != null)
     {
         socket.Dispose(); socket = null;
     }
     if (listeningTask != null)
     {
         listeningTask = null;
     }
 }
コード例 #29
0
ファイル: XHRProxy.cs プロジェクト: zayfal/titanium_mobile
        private async void requestError(DataWriter writer, StreamSocket socket, string status, string message = "")
        {
            writer.WriteString("HTTP/1.0 " + status + "\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n" + message);
            await writer.StoreAsync();

            socket.Dispose();
        }
コード例 #30
0
        private async void ConnectToDevice(PeerInformation peer)
        {
            if (_socket != null)
            {
                // Disposing the socket with close it and release all resources associated with the socket
                _socket.Dispose();
            }

            try
            {
                _socket = new StreamSocket();
                string serviceName = (String.IsNullOrWhiteSpace(peer.ServiceName)) ? tbServiceName.Text : peer.ServiceName;

                // Note: If either parameter is null or empty, the call will throw an exception
                await _socket.ConnectAsync(peer.HostName, serviceName);

                // If the connection was successful, the RemoteAddress field will be populated
                MessageBox.Show(String.Format(AppResources.Msg_ConnectedTo, _socket.Information.RemoteAddress.DisplayName));
            }
            catch (Exception ex)
            {
                // In a real app, you would want to take action dependent on the type of
                // exception that occurred.
                MessageBox.Show(ex.Message);

                _socket.Dispose();
                _socket = null;
            }
        }