Inheritance: IStreamSocket, IClosable
        public async void ConnectAsync(string ipOrHost, int port, SocketEventArgs args)
        {
            _socket = new StreamSocket();
            var server = new HostName(ipOrHost);

            // TCP timeouts in WinRT are excessive, shorten them here using task cancellation
            var cts = new CancellationTokenSource();

            try
            {
                cts.CancelAfter(MqttProtocolInformation.Settings.NetworkTimeout * 1000);
                _logger.LogMessage("Socket", LogLevel.Verbose, string.Format("Authenticating client certificate with remote host CN={0}", server.CanonicalName));
                await _socket.ConnectAsync(server, port.ToString(), GetSocketProtectionLevel(args.EncryptionLevel)).AsTask(cts.Token);
                _clientUid = args.ClientUid;
                StartReceiving();
            }
            catch (TaskCanceledException)
            {
                args.SocketException = new IOException("Timeout error while trying to connect.");
                _clientUid = null;
                _socket.Dispose();
                _socket = null;
            }
            catch (Exception ex)
            {
                args.SocketException = ex;
                _clientUid = null;
                _socket.Dispose();
                _socket = null;
            }
            args.Complete();
        }
示例#2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MailKit.Net.Smtp.SmtpStream"/> class.
 /// </summary>
 /// <remarks>
 /// Creates a new <see cref="SmtpStream"/>.
 /// </remarks>
 /// <param name="source">The underlying network stream.</param>
 /// <param name="socket">The underlying network socket.</param>
 /// <param name="protocolLogger">The protocol logger.</param>
 public SmtpStream(Stream source, Socket socket, IProtocolLogger protocolLogger)
 {
     logger      = protocolLogger;
     IsConnected = true;
     Stream      = source;
     Socket      = socket;
 }
    public async void SendMessage(string message)
    {
        Windows.Networking.Sockets.StreamSocket streamSocket = null;
        streamSocket = new Windows.Networking.Sockets.StreamSocket();
        try
        {
            Debug.Log("Trying to connect");
            await streamSocket.ConnectAsync(HostAddress, "1337");

            Debug.Log("Connected!");
            Stream       streamOut = streamSocket.OutputStream.AsStreamForWrite();
            StreamWriter writer    = new StreamWriter(streamOut);
            await writer.WriteLineAsync(message);

            Debug.Log("The following message was sent: " + message);
            await writer.FlushAsync();

            //creat input stream and read it into a string (for responses from RPI3)

            /*Stream streamIn = streamSocket.InputStream.AsStreamForRead();
             * StreamReader reader = new StreamReader(streamIn);
             * string response = await reader.ReadLineAsync();*/
        }
        catch (Exception e)
        {
            //catch an error messages and display
            Debug.Log(e.Message);
        }
        finally
        {
            //end by disposing the socket and clearing the resources
            streamSocket.Dispose();
        }
    }
示例#4
0
    public void StopExchange()
    {
        exchangeStopRequested = true;

#if UNITY_EDITOR
        if (exchangeThread != null)
        {
            exchangeThread.Abort();
            stream.Close();
            client.Close();
            writer.Close();
            reader.Close();

            stream         = null;
            exchangeThread = null;
        }
#else
        if (exchangeTask != null)
        {
            exchangeTask.Wait();
            socket.Dispose();
            writer.Dispose();
            reader.Dispose();

            socket       = null;
            exchangeTask = null;
        }
#endif
        writer = null;
        reader = null;
    }
示例#5
0
 void PeerFinder_TriggeredConnectionStateChanged(object sender, TriggeredConnectionStateChangedEventArgs args)
 {
     switch (args.State)
     {
         case TriggeredConnectState.Listening:
             Deployment.Current.Dispatcher.BeginInvoke(() =>
     state.Text = "Listening");
             // 作为主机正在监听等待连接
             break;
         case TriggeredConnectState.PeerFound:
             Deployment.Current.Dispatcher.BeginInvoke(() =>
    state.Text = "PeerFound");
             // 触碰完成
             break;
         case TriggeredConnectState.Connecting:
             // 正在连接
             break;
         case TriggeredConnectState.Completed:
             // 连接完成返回 StreamSocket对象可用于进行收发消息
             _streamSocket = args.Socket;
             break;
         case TriggeredConnectState.Canceled:
             //在完成之前,连接已停止
             break;
         case TriggeredConnectState.Failed:
             // 连接失败
             break;
     }
 }
        public BluetoothStreamWrapper(StreamSocket streamSocket)
        {
            _streamSocket = streamSocket;

            _readStream = streamSocket.InputStream.AsStreamForRead(0);
            _writeStream = streamSocket.OutputStream.AsStreamForWrite(0);
        }
        public ExternalAdmin(StreamSocket socket)
        {
            this.socketHandler = new SocketHandler(socket);

            this.socketHandler.OnMessageBytesReceived += SocketHandler_OnMessageBytesReceived;
            this.socketHandler.Start();
        }
        /// <summary>
        /// 處理當ConnectionReceived 的時候
        /// </summary>
        /// <param name="socket"></param>
        private async void ProcessRequestAsync(StreamSocket socket)
        {
            // this works for text only
            StringBuilder request = new StringBuilder();
            using (IInputStream input = socket.InputStream)
            {
                byte[] data = new byte[BufferSize];
                IBuffer buffer = data.AsBuffer();
                uint dataRead = BufferSize;
                while (dataRead == BufferSize)
                {
                    await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
                    request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                    dataRead = buffer.Length;
                }
            }

            using (IOutputStream output = socket.OutputStream)
            {
                string requestMethod = request.ToString().Split('\n')[0];
                string[] requestParts = requestMethod.Split(' ');

                if (requestParts[0] == "GET")
                    await WriteResponseAsync(requestParts[1], output);
                else
                    throw new InvalidDataException("HTTP method not supported: "
                                                   + requestParts[0]);
            }
        }
		public WinRtTransferHandler(StreamSocket socket)
		{
			if (socket == null) throw new ArgumentNullException("socket");

			_reader = new DataReader(socket.InputStream);
			_writer = new DataWriter(socket.OutputStream);
		}
示例#10
0
 internal async Task<HttpRequest> ParseRequestStream(StreamSocket httpRequestSocket)
 {
     using (var inputStream = httpRequestSocket.InputStream)
     {
         return await ParseRequestStream(inputStream);
     }
 }
示例#11
0
 /// <summary>
 /// Creates a new instance of SmtpSocket.
 /// </summary>
 /// <param name="server">Server host name.</param>
 /// <param name="port">Port (usually 25).</param>
 /// <param name="ssl">SSL/TLS support.</param>
 public SmtpSocket(string server, int port, bool ssl)
 {
     _host = new HostName(server);
     _socket = new StreamSocket();
     _port = port;
     _ssl = ssl;
 }
示例#12
0
        private async void ProcessRequestAsync(StreamSocket socket)
        {
            weatherShield.GreenLEDPin.Write(GpioPinValue.High);
            // Read in the HTTP request, we only care about type 'GET'
            StringBuilder request = new StringBuilder();
            using (IInputStream input = socket.InputStream)
            {
                byte[] data = new byte[bufLen];
                IBuffer buffer = data.AsBuffer();
                uint dataRead = bufLen;
                while (dataRead == bufLen)
                {
                    await input.ReadAsync(buffer, bufLen, InputStreamOptions.Partial);
                    request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                    dataRead = buffer.Length;
                }
            }

            using (IOutputStream output = socket.OutputStream)
            {
                string requestMethod = request.ToString().Split('\n')[0];
                string[] requestParts = requestMethod.Split(' ');
                await WriteResponseAsync(requestParts, output);
            }
            weatherShield.GreenLEDPin.Write(GpioPinValue.Low);
        }
示例#13
0
 /// <summary>
 /// Attempt to create a tcp connection to a certain host
 /// </summary>
 /// <param name="remoteAddress">Address of the remote host</param>
 /// <param name="connectionTimeout">Time (in milliseconds) that defines how long we should attempt to connect to the other party</param>
 /// <returns>Returns a StreamSocket to the remote host</returns>
 private async Task<StreamSocket> Connect(string remoteAddress, int connectionTimeout)
 {
     StreamSocket streamSocket = new StreamSocket();
     // Make sure a timeout occurs (otherwise it will try to connect forever)
     CancellationTokenSource cts = new CancellationTokenSource();
     try
     {
         cts.CancelAfter(connectionTimeout);
         // Try to connect to the remote address
         await streamSocket.ConnectAsync(new HostName(remoteAddress), this.port).AsTask(cts.Token);
         return streamSocket;
     }
     catch (TaskCanceledException ex)
     {
         // TaskCanceledException will be thrown when the timeout has passed. 
         // Now throw our own exception
         throw new ConnectionTimedOutException("Could not create connection with host " + remoteAddress + " within the given time-out period of " + connectionTimeout + "ms. ");
     }
     catch (System.Exception ex)
     {
         // Catch any other exception too
         System.Diagnostics.Debug.WriteLine("Exception occured in TCPSocketClient.Connect: " + ex);
         throw;
     }
 }
示例#14
0
        public async void Initialize()
        {
            // Enumerate devices with the object push service
            var services =
                await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(
                    RfcommDeviceService.GetDeviceSelector(
                        RfcommServiceId.ObexObjectPush));

            if (services.Count > 0)
            {
                // Initialize the target Bluetooth BR device
                var service = await RfcommDeviceService.FromIdAsync(services[0].Id);

                // Check that the service meets this App's minimum requirement
                if (SupportsProtection(service) && IsCompatibleVersion(service))
                {
                    _service = service;

                    // Create a socket and connect to the target
                    _socket = new StreamSocket();
                    await _socket.ConnectAsync(
                        _service.ConnectionHostName,
                        _service.ConnectionServiceName,
                        SocketProtectionLevel
                        .BluetoothEncryptionAllowNullAuthentication);

                    // The socket is connected. At this point the App can wait for
                    // the user to take some action, e.g. click a button to send a
                    // file to the device, which could invoke the Picker and then
                    // send the picked file. The transfer itself would use the
                    // Sockets API and not the Rfcomm API, and so is omitted here for
                    // brevity.
                }
            }
        }
示例#15
0
        private async void ProcessRequestAsync(StreamSocket socket)
        {
            // Read in the HTTP request, we only care about type 'GET'
            StringBuilder request = new StringBuilder();
            using (IInputStream input = socket.InputStream)
            {
                byte[] data = new byte[bufLen];
                IBuffer buffer = data.AsBuffer();
                uint dataRead = bufLen;
                while (dataRead == bufLen)
                {
                    await input.ReadAsync(buffer, bufLen, InputStreamOptions.Partial);
                    request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                    dataRead = buffer.Length;
                }
                if (RecivedMeg != null)
                {
                    Debug.WriteLine(request.ToString());
                    RecivedMeg(request.ToString(), EventArgs.Empty);
                }
            }

            using (IOutputStream output = socket.OutputStream)
            {
                string requestMethod = request.ToString().Split('\n')[0];
                string[] requestParts = requestMethod.Split(' ');
                await WriteResponseAsync(requestParts, output);
            }
        }
 private async void ConnectSocket_Click(object sender, RoutedEventArgs e)
 {
     if (string.IsNullOrEmpty(ServiceNameForConnect.Text))
     {
         rootPage.NotifyUser("请提供服务器名", NotifyType.ErrorMessage);
         return;
     }
     HostName hostName;
     try
     {
         hostName = new HostName(HostNameForConnect.Text);
     }
     catch (ArgumentException)
     {
         rootPage.NotifyUser("错误:无效主机名", NotifyType.ErrorMessage);
         return;
     }
     rootPage.NotifyUser("连接至" + HostNameForConnect.Text, NotifyType.StatusMessage);
     using (StreamSocket socket = new StreamSocket())
     {
         socket.Control.ClientCertificate = null;
         bool shouldRetry = await TryConnectSocketWithRetryAsync(socket, hostName);
         if (shouldRetry)
         {
             await TryConnectSocketWithRetryAsync(socket, hostName);
         }
     }
 }
示例#17
0
        private async void ReceiveImage(StreamSocket socket)
        {
            UpdateStatus("Empfange Daten...");

            // DataReader erzeugen, um arbeiten mit Bytes zu vereinfachen
            var reader = new DataReader(socket.InputStream);

            // Anzahl der Bytes abrufen, aus denen das Bild besteht
            // Anzahl = int = 4 Bytes => 4 Bytes vom Socket laden
            await reader.LoadAsync(4);
            int imageSize = reader.ReadInt32();

            // Bytearray des Bildes laden
            await reader.LoadAsync((uint)imageSize);
            byte[] imageBytes = new byte[imageSize];
            reader.ReadBytes(imageBytes);

            // Bytearray in Stream laden und anzeigen
            Dispatcher.BeginInvoke(() =>
            {
                using (var ms = new MemoryStream(imageBytes))
                {
                    var image = new BitmapImage();
                    image.SetSource(ms);

                    ReceivedImage.Source = image;
                }
            });
            UpdateStatus("Bild empfangen.");

            // Ressourcen freigeben
            reader.Dispose();
        }
示例#18
0
 /// <summary>
 /// Initialize the manager, should be called in OnNavigatedTo of main page.
 /// </summary>
 public void Initialize()
 {
     socket = new StreamSocket();
     dataReadWorker = new BackgroundWorker();
     dataReadWorker.WorkerSupportsCancellation = true;
     dataReadWorker.DoWork += new DoWorkEventHandler(ReceiveMessages);
 }
        public ConnectionStatus ConnectToSignalingServer(ConnectionOwner connectionOwner)
        {
            try
            {
                SignaledPeerData.Reset();
                SignalingStatus.Reset();
                SignaledRelayMessages.Reset();

                var socket = new StreamSocket();
                socket.EnableTransferOwnership(Guid.Parse(connectionOwner.OwnerId),
                    SocketActivityConnectedStandbyAction.Wake);
                socket.ConnectAsync(new HostName(SignalingSettings.SignalingServerHost),
                    SignalingSettings.SignalingServerPort, SocketProtectionLevel.PlainSocket)
                    .AsTask()
                    .Wait();
                socket.TransferOwnership(SignalingSocketOperation.SignalingSocketId);
                return new ConnectionStatus
                {
                    IsConnected = true
                };
            }
            catch (Exception exception)
            {
                return new ConnectionStatus
                {
                    IsConnected = false
                };
            }
        }
示例#20
0
 public StateObject(StreamSocket listener, int id = -1)
 {
     this.listener = listener;
     this.id = id;
     this.Close = false;
     this.Reset();
 }
示例#21
0
        public static HttpRequest Read(StreamSocket socket)
        {
            HttpRequest request = new HttpRequest();

            using (var input = socket.InputStream)
            {
                using (var reader = new StreamReader(input.AsStreamForRead()))
                {
                    var requestHeader = reader.ReadLine();

                    var headerSegments = requestHeader.Split(' ');
                    request.Method = new HttpMethod(headerSegments[0]);
                    request.Path = new Uri(headerSegments[1], UriKind.RelativeOrAbsolute);
                    request.Version = GetHttpVersion(headerSegments[2]);

                    if (request.Version.Equals(HttpVersion.Http10))
                        request.Headers.Add("Host", $"{socket.Information.LocalAddress}:{socket.Information.LocalPort}");


                    ParseRequest(reader, request);

                    if (!request.Path.IsAbsoluteUri)
                        request.Path = new UriBuilder("http", socket.Information.LocalAddress.ToString(), int.Parse(socket.Information.LocalPort), request.Path.OriginalString).Uri;
                }
            }

            return request;
        }
 public WindowsNetSockets(string host, int port, bool ssl)
 {
     Socket = new StreamSocket();
     Host = host;
     Port = port;
     Ssl = ssl;
 }
示例#23
0
        private async void ProcessRequestAsync(StreamSocket socket)
        {
            HttpRequest request;
            try
            {
                request = HttpRequest.Read(socket);
            }
            catch (Exception ex)
            {
                await WriteInternalServerErrorResponse(socket, ex);
                return;
            }

            if (AcceptedVerbs.Contains(request.Method.Method))
            {
                HttpResponse response;
                try
                {
                    response = await restHandler.Handle(request);
                }
                catch (Exception ex)
                {
                    await WriteInternalServerErrorResponse(socket, ex);
                    return;
                }
                await WriteResponse(response, socket);

                await socket.CancelIOAsync();
                socket.Dispose();
            }
        }
 //Connects to server
 public async Task connect(string address, int port)
 {
     if (!this.connected)
     {
         try
         {
             this.socket = new StreamSocket();
             this.hostname = new HostName(address);
             this.port = port;
             await this.socket.ConnectAsync(this.hostname, port.ToString());
             this.writer = new DataWriter(this.socket.OutputStream);
             this.reader = new DataReader(this.socket.InputStream);
             this.reader.InputStreamOptions = InputStreamOptions.Partial;
             connected = true;
         }
         catch (Exception e)
         {
             connected = false;
             Debug.WriteLine(e.Message);
         }
     }
     else
     {
         await new MessageDialog("Already connected", "Information").ShowAsync();
         connected = true;
         
     }
 }
示例#25
0
        public static async Task<bool> CheckServerAddressWP(string url, int port = 80, int msTimeout = 5000)
        {
            bool retVal = false;
            string originalUrl = url;

            if (!IsUrlValid(url))
                return retVal;

            try
            {
                using (var tcpClient = new StreamSocket())
                {
                    url = url.Replace("http://", string.Empty).Replace("https://", string.Empty);
                    if (url.Last() == '/')
                        url = url.Substring(0, url.Length - 1);

                    await tcpClient.ConnectAsync(new Windows.Networking.HostName(url), port.ToString(), SocketProtectionLevel.PlainSocket);

                    if (tcpClient.Information.RemoteHostName.ToString().ToLower() == url.ToLower())
                        retVal = true;

                    tcpClient.Dispose();
                }
            }
            catch (Exception ex)
            {
                retVal = false;
            }

            retVal &= await ExposesContosoMomentsWebAPIs(originalUrl);

            return retVal;
        }
        public SocketHandler(StreamSocket socket)
        {
            this.socket = socket;

            this.reader = new DataReader(this.socket.InputStream);
            this.writer = new DataWriter(this.socket.OutputStream);
        }
示例#27
0
        public static void Connect(string address, string port)
        {
            if (!connected)
            {
                clientSocket = new StreamSocket();

                try
                {
                    serverHost = new HostName(address);
                    serverPort = port;
                    serverHostnameString = address;
                    writer = new DataWriter(clientSocket.OutputStream);

                    clientSocket.ConnectAsync(serverHost, serverPort);
                    connected = true;
                }
                catch (Exception)
                {
                    clientSocket.Dispose();
                    clientSocket = null;

                    throw new ConnectionErrorException();
                }
            }
            else
            {
                clientSocket.Dispose();
                clientSocket = null;
                connected = false;

                GamepadClient.Connect(address, port);
            }
        }
示例#28
0
        public async Task Connect()
        {
            PeerFinder.AlternateIdentities["Bluetooth:SDP"] = ServiceGUID.ToString();
            var peers = await PeerFinder.FindAllPeersAsync();

            foreach (var p in peers)
            {
                var h = p.ServiceName;
            }

            // TODO: obviously list these instead of taking the first
            var peer = peers.FirstOrDefault();

            if (peer != null)
            {
                var socket = new StreamSocket();
                try
                {
                    // default service name?
                    await socket.ConnectAsync(peer.HostName, ServiceName);

                    var connection = new DuplexConnection(socket);
                    var device = new BluetoothDevice(peer.DisplayName, peer.HostName, peer.ServiceName);

                    if (ConnectionEstablished != null)
                    {
                        ConnectionEstablished(this, new ClientConnectedEventArgs(device, connection));
                    }
                } 
                catch (Exception ex)
                {
                    
                }
            }
        }
示例#29
0
        private async void ProcessRequestAsync(StreamSocket socket)
        {
            if(!inited)
            {
                // start the temp sensor here...
                // for some reason when I put it earlier init was getting called twice
                // and so it would fail the second time.  Maybe an async bug with iot?
                TemperatureSensors.InitSensors();
                inited = true;
            }

            try
            {
                System.Diagnostics.Debug.WriteLine("ProcessRequestAsync called...");
                StringBuilder request = new StringBuilder();
                //Get the incomming data
                using (IInputStream input = socket.InputStream)
                {
                    byte[] data = new byte[BufferSize];
                    IBuffer buffer = data.AsBuffer();
                    uint dataRead = BufferSize;
                    //Read all the incomming data
                    while (dataRead == BufferSize)
                    {
                        await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
                        request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                        dataRead = buffer.Length;
                    }
                }

                //Got the data start processing a response
                using (IOutputStream output = socket.OutputStream)
                {
                    string requestMethod = request.ToString();
                    string[] requestParts = { "" };
                    if (requestMethod != null)
                    {
                        //Beakup the first line of the request into it parts
                        requestParts = requestMethod.Split('\n')[0].Split(' ');
                    }
                    //We only respond HTTP GETS and POST methods
                    if (requestParts[0] == "GET" && requestParts.Length > 1)
                        await WriteGetResponseAsync(requestParts[1], output);
                    else if (requestParts[0] == "POST" && requestParts.Length > 1)
                    {
                        // parse out any json
                        int istart = requestMethod.IndexOf("[{");
                        int iend = requestMethod.IndexOf("}]");
                        int len = iend - istart + 2;
                        string json = null;
                        if(istart > 0 && len > 0)
                            json = requestMethod.Substring(istart, len);
                        await WritePostResponseAsync(requestParts[1], output, json);
                    }
                    else
                        await WriteMethodNotSupportedResponseAsync(requestParts[0], output);
                }
            }
            catch (Exception) { }
        }
示例#30
0
		protected override Task CloseStreamAsync(System.IO.Stream stream)
		{
			stream.Dispose();
			m_socket.Dispose();
			m_socket = null;
			return Task.FromResult(true);
		}
 private async Task HandleRequests(StreamSocket client)
 {
     using (client)
     {
         await HandleRequest(client);
     }
 }
        private async void ProcessRequestAsync(StreamSocket socket)
        {
            try
            {
                // Read in the HTTP request, we only care about type 'GET'
                StringBuilder request = new StringBuilder();
                using (IInputStream input = socket.InputStream)
                {
                    byte[] data = new byte[bufLen];
                    IBuffer buffer = data.AsBuffer();
                    uint dataRead = bufLen;
                    while (dataRead == bufLen)
                    {
                        await input.ReadAsync(buffer, bufLen, InputStreamOptions.Partial);
                        request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                        dataRead = buffer.Length;
                    }
                }

                using (IOutputStream output = socket.OutputStream)
                {
                    string requestMethod = request.ToString().Split('\n')[0];
                    string[] requestParts = requestMethod.Split(' ');
                    await WriteResponseAsync(requestParts, output);
                }
            }
            catch (Exception ex)
            {
                await LogExceptionAsync(nameof(ProcessRequestAsync), ex);
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
            }
        }
示例#33
0
        public TcpTextWriter(string hostName, int port)
        {
            if (hostName == null)
                throw new ArgumentNullException(nameof(hostName));
            if ((port < 0) || (port > ushort.MaxValue))
                throw new ArgumentException("port");

            HostName = hostName;
            Port = port;

#if __IOS__ || MAC
            UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
#endif
            try
            {
#if __IOS__ || MAC || ANDROID
                var client = new TcpClient(hostName, port);
                writer = new StreamWriter(client.GetStream());
#elif WINDOWS_PHONE || NETFX_CORE
               
                var socket = new StreamSocket();
                socket.ConnectAsync(new HostName(hostName), port.ToString(CultureInfo.InvariantCulture))
                    .AsTask()
                    .ContinueWith( _ => writer = new StreamWriter(socket.OutputStream.AsStreamForWrite()));
#endif
            }
            catch
            {
#if __IOS__ || MAC
                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
#endif
                throw;
            }
        }
示例#34
0
 public async void SendMessage(string msg)
 {
     HostName hostName;
     try
     {
         hostName = new HostName("localhost");
     }
     catch (ArgumentException)
     {
         return;
     }
     StreamSocket socket;
     try
     {
         using (socket = new StreamSocket())
         {
             await socket.ConnectAsync(hostName, port2);
             //CoreApplication.Properties.Add("connected", null);
             DataWriter dw = new DataWriter(socket.OutputStream);
             dw.WriteString(msg);
             await dw.StoreAsync();
         }
     }
     catch
     {
         //break;
     }
 }
示例#35
0
文件: Server.cs 项目: sm6uax/plegma
        public bool Start(int Port)
#endif
        {
            lock (this)
            {
                //keep
                this.Port = Port;

                //get certificate
#if NETFX
                this._certificate = certificate;
                if (Certificate != null && !Certificate.HasPrivateKey)
                {
                    DebugEx.Assert("Not private key found in servers certificate");
                    return(false);
                }
#endif

                //create socket and bind
                try
                {
#if NETFX
                    sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    sock.Bind(new IPEndPoint(IPAddress.Any, Port));
#elif UNIVERSAL
                    sock = new StreamSocketListener();
                    sock.ConnectionReceived += Sock_ConnectionReceived;
                    sock.BindServiceNameAsync(Port.ToStringInvariant()).AsTask().Wait();
#endif
                }
                catch (Exception ex)
                {
                    DebugEx.Assert(ex, "YPServer failed to bind port " + Port);
                    return(false);
                }

                //mark running
                _IsRunning = true;

                //log
#if NETFX
                DebugEx.TraceLog("YPServer (socks) started on port " + Port + "  (Secure=" + (certificate != null).ToStringInvariant() + ")");
#elif UNIVERSAL
                DebugEx.TraceLog("YPServer (socks) started on port " + Port + "  (Secure= False)");
#endif
                //start port listener
#if NETFX
                PortListener              = new Thread(PortListenerEntryPoint);
                PortListener.Name         = "YPC Server PortListener thread";
                PortListener.IsBackground = true;
                PortListener.Start();
#endif
                //done
                return(true);
            }
        }
示例#36
0
 void DropConnection()
 {
     if (Socket != null)
     {
         try {
             Socket.Dispose();
         } catch {
             return;
         }
     }
 }
示例#37
0
文件: Server.cs 项目: sm6uax/plegma
        //------------------------------------------------------------------------------------------------------------------------
        public void Stop(bool CloseAllChannels = false)
        {
            try
            {
                lock (this)
                {
                    //close all channels
                    if (CloseAllChannels)
                    {
                        _Channels.ForEach(c => { try { c.Close("Server stopped"); } catch (Exception ex) { DebugEx.Assert(ex, "Error while closing channel"); } });
                        _Channels.Clear();
                    }

                    //update flag
                    if (!_IsRunning)
                    {
                        return;
                    }
                    else
                    {
                        _IsRunning = false;
                    }

                    //close my socket
                    try
                    {
                        if (sock != null)
                        {
#if NETFX
                            try { sock.Close(); } catch { }
#endif
                            try { sock.Dispose(); } catch { }
                        }
                    }
                    catch (Exception ex)
                    {
                        DebugEx.TraceErrorException(ex);
                    }
                    sock = null;

                    //wait for task finish
#if NETFX
                    PortListener?.Join(1000);
#elif UNIVERSAL
                    PortListener?.Wait(1000);
#endif
                    PortListener = null;
                }
            }
            catch (Exception ex)
            {
                DebugEx.Assert(ex, "YPChannel Server Stop() failed");
            }
        }
示例#38
0
        void DropConnection()
        {
            if (Socket != null)
            {
#if NETSTANDARD_2_0 || NET_4_5 || __MOBILE__
                Socket.Disconnect(false);
#else
                Socket.Dispose();
#endif
            }
        }
示例#39
0
        // Reference socket streams for writing and reading messages.
        private void SendOrReceiveSong(Windows.Networking.Sockets.StreamSocket socket)
        {
            _proximitySocket = socket;

            if (!_sd._haveSong)
            {
                ReceiveSongFromSocket();
            }
            else
            {
                SendSongOverSocket();
            }
        }
示例#40
0
        /// <summary>
        /// Creates the stream the GrblDevice is working on top off.
        /// </summary>
        /// <returns></returns>
        protected override async Task <System.IO.Stream> OpenStreamAsync()
        {
            var socket = new Windows.Networking.Sockets.StreamSocket();
            await socket.ConnectAsync(
#if NETFX_CORE
                m_device.ConnectionHostName,
                m_device.ConnectionServiceName);
#else
                m_device.HostName, "1");
#endif
            m_socket = socket;
            return(socket.InputStream.AsStreamForRead());
        }
        private async void StartClient()
        {
            try
            {
                // Create the StreamSocket and establish a connection to the echo server.
                using (var streamSocket = new Windows.Networking.Sockets.StreamSocket())
                {
                    // The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process.
                    var hostName = new Windows.Networking.HostName("localhost");

                    this.clientListBox.Items.Add("client is trying to connect...");

                    await streamSocket.ConnectAsync(hostName, StreamSocketAndListenerPage.PortNumber);

                    this.clientListBox.Items.Add("client connected");

                    // Send a request to the echo server.
                    string request = "Hello, World!";
                    using (Stream outputStream = streamSocket.OutputStream.AsStreamForWrite())
                    {
                        using (var streamWriter = new StreamWriter(outputStream))
                        {
                            await streamWriter.WriteLineAsync(request);

                            await streamWriter.FlushAsync();
                        }
                    }

                    this.clientListBox.Items.Add(string.Format("client sent the request: \"{0}\"", request));

                    // Read data from the echo server.
                    string response;
                    using (Stream inputStream = streamSocket.InputStream.AsStreamForRead())
                    {
                        using (StreamReader streamReader = new StreamReader(inputStream))
                        {
                            response = await streamReader.ReadLineAsync();
                        }
                    }

                    this.clientListBox.Items.Add(string.Format("client received the response: \"{0}\" ", response));
                }

                this.clientListBox.Items.Add("client closed its socket");
            }
            catch (Exception ex)
            {
                Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
                this.clientListBox.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message);
            }
        }
        async private void ConnectToPeer(Windows.Networking.Proximity.PeerInformation peerInfo)
        {
            //WriteMessageText("Peer found. Connecting to " + peerInfo.DisplayName + "\n");
            try {
                Windows.Networking.Sockets.StreamSocket socket =
                    await Windows.Networking.Proximity.PeerFinder.ConnectAsync(peerInfo);

                //WriteMessageText("Connection successful. You may now send messages.\n");
                this.thingsFound.Text += "Connection successful. You may now send messages.";
                //SendMessage(socket);
            }
            catch (Exception err) {
                //WriteMessageText("Connection failed: " + err.Message + "\n");
            }
        }
        void OnConnectionReceivedAsync(
            StreamSocketListener listener,
            StreamSocketListenerConnectionReceivedEventArgs args)
        {
            // Stop advertising/listening so that we're only serving one client
            _provider.StopAdvertising();
            listener.Dispose();
            _socket = args.Socket;

            // The client socket is connected. At this point the App can wait for
            // the user to take some action, for example, click a button to receive a file
            // from the device, which could invoke the Picker and then save the
            // received file to the picked location. The transfer itself would use
            // the Sockets API and not the Rfcomm API, and so is omitted here for
            // brevity.
        }
示例#44
0
        /// <summary>
        /// Creates the stream the NmeaDevice is working on top off.
        /// </summary>
        /// <returns></returns>
        protected override async Task <System.IO.Stream> OpenStreamAsync()
        {
            var socket = new Windows.Networking.Sockets.StreamSocket();

#if WINDOWS_UWP
            if (m_devicePeer != null)
            {
                await socket.ConnectAsync(m_devicePeer.HostName, "1");
            }
            else
#endif
            {
                await socket.ConnectAsync(m_deviceService.ConnectionHostName, m_deviceService.ConnectionServiceName);
            }
            m_socket = socket;
            return(socket.InputStream.AsStreamForRead());
        }
示例#45
0
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Windows.Networking.Sockets.StreamSocket streamSocket = new Windows.Networking.Sockets.StreamSocket();
            HostName      localHost  = new HostName("localhost");
            HostName      remoteHost = new HostName("www.andrea-allievi.com");
            EndpointPair  ep         = new EndpointPair(localHost, "", remoteHost, "80");
            MessageDialog dlg        = new Windows.UI.Popups.MessageDialog("");

            // Save the socket, so subsequent steps can use it.
            Windows.ApplicationModel.Core.CoreApplication.Properties.Add("clientSocket", streamSocket);

            try
            {
                await streamSocket.ConnectAsync(remoteHost, "80");
            }
            catch (Exception exc)
            {
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(exc.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                dlg.Title   = "Socket Error!";
                dlg.Content = "Connect failed with error: " + exc.Message;
                dlg.ShowAsync();
                return;
            }

            DataWriter writer = new DataWriter(streamSocket.OutputStream);

            writer.WriteString("GET /index.html\r\n");
            await writer.StoreAsync();

            DataReader reader = new DataReader(streamSocket.InputStream);
            uint       len    = 2048;

            reader.InputStreamOptions = InputStreamOptions.Partial;
            uint numStrBytes = await reader.LoadAsync(len);

            string data = reader.ReadString(numStrBytes);

            dlg.Title   = "Received data";
            dlg.Content = data;
            await dlg.ShowAsync();
        }
示例#46
0
    /// <summary>
    /// established a TCP socket connection to receive packets from another device.
    /// This is used when running as a UWP app on the HoloLens.
    /// </summary>
    private async void ConnectSocketUWP()
    {
        try
        {
            socket = new Windows.Networking.Sockets.StreamSocket();
            Windows.Networking.HostName serverHost = new Windows.Networking.HostName(ipAddress);
            await socket.ConnectAsync(serverHost, portUWP);

            Stream streamIn = socket.InputStream.AsStreamForRead();
            reader     = new StreamReader(streamIn, Encoding.UTF8);
            connection = true;
        }

        catch (Exception e)
        {
            //do something
        }
    }
示例#47
0
        /// <summary>
        /// Resolve the GEForce PC hostname to an IP Address
        /// </summary>
        /// <param name="hostName">Hostname to resolve</param>
        private async Task ResolveHostName(String hostName)
        {
            HostName     serverHost   = new HostName(hostName);
            StreamSocket clientSocket = new Windows.Networking.Sockets.StreamSocket();

            // Try to connect to the remote host
            try
            {
                await clientSocket.ConnectAsync(serverHost, "http");
            }
            // TODO properly handle this exception
            catch (Exception e)
            {
                Debug.WriteLine("Exception: " + e.Message);
            }

            this.ServerIP = clientSocket.Information.RemoteAddress.ToString();
        }
    public void StopExchange()
    {
        exchangeStopRequested = true;

        if (exchangeTask != null)
        {
            exchangeTask.Wait();
            socket.Dispose();
            writer.Dispose();
            reader.Dispose();

            socket       = null;
            exchangeTask = null;
        }

        writer = null;
        reader = null;
    }
示例#49
0
        /// <summary>
        /// Resolve the GEForce PC hostname to an IP Address
        /// </summary>
        /// <param name="hostName">Hostname to resolve</param>
        private async Task <String> ResolveHostName(String hostName)
        {
            HostName     serverHost   = new HostName(hostName);
            StreamSocket clientSocket = new Windows.Networking.Sockets.StreamSocket();

            // Try to connect to the remote host
            try
            {
                await clientSocket.ConnectAsync(serverHost, "47984");
            }
            catch (Exception e)
            {
                Debug.WriteLine("ResolveHostName Exception: " + e.Message);
                return(null);
            }

            return(clientSocket.Information.RemoteAddress.ToString());
        }
示例#50
0
    public void StopExchange()
    {
        writer.Write("!\n");

        //if (exchangeTask != null) {
        //    exchangeTask.Wait();

        socket.Dispose();
        writer.Dispose();
        reader.Dispose();

        socket       = null;
        exchangeTask = null;
        //}

        writer = null;
        reader = null;
    }
示例#51
0
    /// <summary>
    /// Permet de déconnecter le client du serveur
    /// </summary>
    private void OnApplicationQuit()
    {
        try {
            // signal shutdown
            stopListening = true;
#if UNITY_EDITOR
            if (conThread == null || stream == null)
            {
                Debug.Log("PlStreamCustom not started, nothing to close");
                return;
            }
            // attempt to join for 500ms
            if (!conThread.Join(500))
            {
                // force shutdown
                conThread.Abort();
                if (tcpClient != null)
                {
                    tcpClient.Close();
                    tcpClient = null;
                }
                stream.Close();
            }
#else
            if (exchangeTask != null)
            {
                exchangeTask.Wait();
                socket.Dispose();
                stream.Close();
                socket       = null;
                exchangeTask = null;
            }
            else
            {
                Debug.Log("PlStreamCustom not started, nothing to close");
            }
#endif
        }
        catch (Exception e) {
            Debug.Log(e);
            Debug.Log("[polhemus] PlStream was unable to close the connection thread upon application exit. This is not a critical exception.");
        }
    }
示例#52
0
    private async void ConnectUWP(string host, string port)
#endif
    {
#if UNITY_EDITOR
        Debug.Log("Can't use UWP TCP client in Unity!");
#else
        try {
            socket = new Windows.Networking.Sockets.StreamSocket();
            Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host);
            await socket.ConnectAsync(serverHost, port);

            stream = socket.InputStream.AsStreamForRead();
            Initialize();
            Debug.Log("Connected!");
        }
        catch (Exception e) {
            Debug.Log(e.ToString());
        }
#endif
    }
示例#53
0
    private async void ConnectUWP(string host, string port)
#endif
    {
#if UNITY_EDITOR
        errorStatus = "UWP TCP client used in Unity!";
#else
        try
        {
            socket = new Windows.Networking.Sockets.StreamSocket();
            Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host);
            await socket.ConnectAsync(serverHost, port);

            streamIn = socket.InputStream.AsStreamForRead();
        }
        catch (Exception e)
        {
            errorStatus = e.ToString();
        }
#endif
    }
示例#54
0
    /// <summary>
    /// Permet de déconnecter le client du serveur
    /// </summary>
    private void OnApplicationQuit()
    {
        try {
            // signal shutdown
            stopListening = true;
#if !UNITY_EDITOR
            if (exchangeTask != null)
            {
                exchangeTask.Wait();
                socket.Dispose();
                stream.Close();
                socket       = null;
                exchangeTask = null;
            }
#endif
        }
        catch (Exception e) {
            Debug.Log(e);
        }
    }
示例#55
0
        public async void StartClient(string Host, string PortNumber)
        {
            try
            {
                // Create the StreamSocket and establish a connection to the echo server.
                using (var streamSocket = new Windows.Networking.Sockets.StreamSocket())
                {
                    var hostName = new Windows.Networking.HostName(Host);

                    await streamSocket.ConnectAsync(hostName, PortNumber);

                    // Send a request to the echo server.
                    string request = "Hello, World!";

                    using (Stream outputStream = streamSocket.OutputStream.AsStreamForWrite())
                    {
                        using (var streamWriter = new StreamWriter(outputStream))
                        {
                            await streamWriter.WriteLineAsync(request);

                            await streamWriter.FlushAsync();
                        }
                    }


                    // Read data from the echo server.
                    string response;
                    using (Stream inputStream = streamSocket.InputStream.AsStreamForRead())
                    {
                        using (StreamReader streamReader = new StreamReader(inputStream))
                        {
                            response = await streamReader.ReadLineAsync();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
            }
        }
示例#56
0
        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="SmtpStream"/> and
        /// optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources;
        /// <c>false</c> to release only the unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && !disposed)
            {
                IsConnected = false;
                Stream.Dispose();
                disposed = true;

#if NETFX_CORE
                if (Socket != null)
                {
                    Socket.Dispose();
                    Socket = null;
                }
#else
                Socket = null;
#endif
            }

            base.Dispose(disposing);
        }
示例#57
0
        public MainPage()
        {
            this.InitializeComponent();

            #region 创建预览
            var compositor = Window.Current.Compositor;
            _previewBrush         = compositor.CreateSurfaceBrush();
            _previewBrush.Stretch = CompositionStretch.Uniform;
            var shadow = compositor.CreateDropShadow();
            shadow.Mask    = _previewBrush;
            _previewVisual = compositor.CreateSpriteVisual();
            _previewVisual.RelativeSizeAdjustment = Vector2.One;
            _previewVisual.Brush  = _previewBrush;
            _previewVisual.Shadow = shadow;
            ElementCompositionPreview.SetElementChildVisual(PreviewGrid, _previewVisual);
            #endregion

            _device = D3DDeviceManager.Device;

            tcpsocket = new StreamSocket();
        }
示例#58
0
        public static async Task StartClient()
        {
            try
            {
                // Create the StreamSocket and establish a connection to the echo server.
                streamSocket = new Windows.Networking.Sockets.StreamSocket();

                // The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process.
                var hostName = new Windows.Networking.HostName("192.168.0.137");

                MainPage.MP.clientListBox.Items.Add("client is trying to connect...");

                await streamSocket.ConnectAsync(hostName, "1234");

                MainPage.MP.clientListBox.Items.Add("client connected");
            }
            catch (Exception ex)
            {
                Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
                MainPage.MP.clientListBox.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message);
            }
        }
示例#59
0
    private async void ConnectUWP(string host, string port)
#endif
    {
#if UNITY_EDITOR
        Debug.Log("UWP TCP client used in Unity!");
#else
        try {
            socket = new Windows.Networking.Sockets.StreamSocket();
            Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host);
            await socket.ConnectAsync(serverHost, port);

            stream = socket.InputStream.AsStreamForRead();
#if !UNITY_EDITOR
            exchangeTask = Task.Run(() => Read_Data());
#endif
            Debug.Log("Connected!");
        }
        catch (Exception e) {
            Debug.Log(e.ToString());
        }
#endif
    }
示例#60
-1
        /// <summary>
        /// Creates the stream the NmeaDevice is working on top off.
        /// </summary>
        /// <returns></returns>
        protected override async Task <System.IO.Stream> OpenStreamAsync()
        {
            var socket = new Windows.Networking.Sockets.StreamSocket();

            socket.Control.KeepAlive = true;
            if (m_devicePeer != null)
            {
                await socket.ConnectAsync(m_devicePeer.HostName, "1");
            }
            else
            {
                await socket.ConnectAsync(m_deviceService.ConnectionHostName, m_deviceService.ConnectionServiceName);
            }
            m_socket = socket;
            return(null); //We're going to use WinRT buffers instead and will handle read/write, so no reason to return a stream. This is mainly done to avoid locking issues reading and writing at the same time
        }