コード例 #1
0
        public Task TcpSocketClient_ShouldThrowPCLException_InPlaceOfNativeSocketException()
        {
            var sut = new TcpSocketClient();
            var unreachableHostName = ":/totallynotvalid@#$";

            return Assert.ThrowsAsync<Exception>(() => sut.ConnectAsync(unreachableHostName, 8000));
        }
コード例 #2
0
        /// <summary>
        ///     Binds the <code>TcpSocketListener</code> to the specified port on all endpoints and listens for TCP connections.
        /// </summary>
        /// <param name="port">The port to listen on. If '0', selection is delegated to the operating system.</param>
        /// <param name="listenOn">The <code>CommsInterface</code> to listen on. If unspecified, all interfaces will be bound.</param>
        /// <returns></returns>
        public Task StartListeningAsync(int port, ICommsInterface listenOn = null)
        {
            if (listenOn != null && !listenOn.IsUsable)
                throw new InvalidOperationException("Cannot listen on an unusable interface. Check the IsUsable property before attemping to bind.");
            
            _listenCanceller = new CancellationTokenSource();
            _backingStreamSocketListener = new StreamSocketListener();

            _backingStreamSocketListener.ConnectionReceived += (sender, args) =>
            {
                var nativeSocket = args.Socket;
                var wrappedSocket = new TcpSocketClient(nativeSocket, _bufferSize);

                var eventArgs = new TcpSocketListenerConnectEventArgs(wrappedSocket);
                if (ConnectionReceived != null)
                    ConnectionReceived(this, eventArgs);
            };

            var sn = port == 0 ? "" : port.ToString();
#if !WP80    
            if (listenOn != null)
            {
                var adapter = ((CommsInterface)listenOn).NativeNetworkAdapter;

                return _backingStreamSocketListener
                            .BindServiceNameAsync(sn, SocketProtectionLevel.PlainSocket, adapter)
                            .AsTask();
            }
            else
#endif
                return _backingStreamSocketListener
                            .BindServiceNameAsync(sn)
                            .AsTask();
        }
コード例 #3
0
        public async Task Initialize(string host, string port, ConnectionChannel connectionChannel, HeartbeatChannel heartbeatChannel, Action<Stream, bool> packetReader)
        {
            if (_client == null) _client = new TcpSocketClient();
            await _client.ConnectAsync(host, int.Parse(port), true, default(CancellationToken), true);


            connectionChannel.OpenConnection();
            heartbeatChannel.StartHeartbeat();

            await Task.Run(() =>
            {
                while (true)
                {
                    var sizeBuffer = new byte[4];
                    byte[] messageBuffer = { };
                    // First message should contain the size of message
                    _client.ReadStream.Read(sizeBuffer, 0, sizeBuffer.Length);
                    // The message is little-endian (that is, little end first),
                    // reverse the byte array.
                    Array.Reverse(sizeBuffer);
                    //Retrieve the size of message
                    var messageSize = BitConverter.ToInt32(sizeBuffer, 0);
                    messageBuffer = new byte[messageSize];
                    _client.ReadStream.Read(messageBuffer, 0, messageBuffer.Length);
                    var answer = new MemoryStream(messageBuffer.Length);
                    answer.Write(messageBuffer, 0, messageBuffer.Length);
                    answer.Position = 0;
                    packetReader(answer, true);
                }
            });
        }
コード例 #4
0
        public async Task TcpSocketClient_ShouldSendReceiveData()
        {
            var bytesToSend = new byte[] {0x1, 0x2, 0x3, 0x4, 0x5};
            var len = bytesToSend.Length;
            var port = PortGranter.GrantPort();

            var listener = new TcpSocketListener();
            await listener.StartListeningAsync(port);

            var tcs = new TaskCompletionSource<bool>();
            listener.ConnectionReceived += async (sender, args) =>
            {
                var bytesReceived = new byte[len];
                await args.SocketClient.ReadStream.ReadAsync(bytesReceived, 0, len);

                var allSame =
                    Enumerable
                        .Zip(bytesToSend,
                            bytesReceived,
                            (s, r) => s == r)
                        .All(b => b);

                tcs.SetResult(allSame);
            };

            var client = new TcpSocketClient();
            await client.ConnectAsync("127.0.0.1", port);
            await client.WriteStream.WriteAsync(bytesToSend, 0, len);

            var ok = await tcs.Task;

            await listener.StopListeningAsync();

            Assert.True(ok);
        }
コード例 #5
0
        public Task TcpSocketClient_ShouldThrowNormalException_WhenNotPlatformSpecific()
        {
            var sut = new TcpSocketClient();
            var tooHighForAPort = Int32.MaxValue;

            return Assert.ThrowsAsync<ArgumentOutOfRangeException>(() => sut.ConnectAsync("127.0.0.1", tooHighForAPort));
        }
コード例 #6
0
        private Task OnlyThrowsSocketExceptionOnNet()
        {
            var sut = new TcpSocketClient();
            var unreachableHostName = ":/totallynotvalid@#$";

            return sut.ConnectAsync(unreachableHostName, 8000);
        }
コード例 #7
0
        private Task OnlyThrowsSocketExceptionOnWinRT()
        {
            var sut = new TcpSocketClient();
            var tooHighForAPort = Int32.MaxValue;

            return sut.ConnectAsync("127.0.0.1", tooHighForAPort);
        }
コード例 #8
0
        public TcpSocketClientPage()
        {
            _client = new TcpSocketClient();
            _messagesSub = new Subject<Message>();
            _messagesObs = _messagesSub.AsObservable();
            

            InitView();
        }
コード例 #9
0
ファイル: Client.cs プロジェクト: fcin/RemindMe
        private async Task SendTcpAsync(ClientInfo clientInfo, byte[] message)
        {
            var client = new TcpSocketClient();
            await client.ConnectAsync(clientInfo.IpAddress, SharedSettings.TcpPort);

            client.WriteStream.Write(message, 0, message.Length);
            await client.WriteStream.FlushAsync();

            await client.DisconnectAsync();
        }
コード例 #10
0
        public async Task TcpSocketClient_ShouldBeAbleToConnect()
        {
            var port = PortGranter.GrantPort();
            var listener = new TcpSocketListener();
            await listener.StartListeningAsync(port);

            var sut = new TcpSocketClient();
            await sut.ConnectAsync("127.0.0.1", port);

            await listener.StopListeningAsync();

            // getting here means nothing went boom
            Assert.True(true);
        }
コード例 #11
0
 private static bool OpenConnection()
 {
     try
     {
         // Send initial parameters
         var networkStream = ImageComparisonServer.WriteStream;
         var binaryWriter = new BinaryWriter(networkStream);
         ImageTestResultConnection.Write(binaryWriter);
         return true;
     }
     catch
     {
         ImageComparisonServer = null;
         return false;
     }
 }
コード例 #12
0
        public static bool Connect()
        {
            if (ImageComparisonServer != null)
                return true;

            try
            {
                ImageComparisonServer = new TcpSocketClient();
                var t = Task.Run(async () => await ImageComparisonServer.ConnectAsync(XenkoImageServerHost, XenkoImageServerPort));
                t.Wait();
            }
            catch (Exception)
            {
                ImageComparisonServer = null;

                return false;
            }

            return OpenConnection();
        }
コード例 #13
0
        public static void Disconnect()
        {
            if (ImageComparisonServer != null)
            {
                try
                {
                    // Properly sends a message notifying we want to close the connection
                    var networkStream = ImageComparisonServer.WriteStream;
                    var binaryWriter = new BinaryWriter(networkStream);
                    binaryWriter.Write((int)ImageServerMessageType.ConnectionFinished);
                    binaryWriter.Flush();

                    ImageComparisonServer.Dispose();
                }
                catch (Exception)
                {
                    // Ignore failures on disconnect
                }
                ImageComparisonServer = null;
            }
        }
コード例 #14
0
 public static bool Connect(SimpleSocket simpleSocket)
 {
     ImageComparisonServer = simpleSocket.Socket;
     return OpenConnection();
 }
コード例 #15
0
#pragma warning disable 4014
        private void WaitForConnections(CancellationToken cancelToken)
        {
            Task.Factory.StartNew(async () =>
            {
                while (!cancelToken.IsCancellationRequested)
                {
                    var nativeClient = await Task.Run(() => _backingTcpListener.AcceptTcpClient(), cancelToken);
                    var wrappedClient = new TcpSocketClient(nativeClient, _bufferSize);

                    var eventArgs = new TcpSocketListenerConnectEventArgs(wrappedClient);
                    if (ConnectionReceived != null)
                        ConnectionReceived(this, eventArgs);
                }
            },
                cancelToken,
                TaskCreationOptions.LongRunning,
                TaskScheduler.Default);
        }
コード例 #16
0
        public async Task StartClient(string address, int port, bool needAck = true)
        {
            // Create TCP client
            var socket = new TcpSocketClient(2048);

            try
            {
                await socket.ConnectAsync(address, port);

                SetSocket(socket);
                //socket.NoDelay = true;

                // Do an ack with magic packet (necessary so that we know it's not a dead connection,
                // it sometimes happen when doing port forwarding because service don't refuse connection right away but only fails when sending data)
                if (needAck)
                    await SendAndReceiveAck(socket, MagicAck, MagicAck);

                Connected?.Invoke(this);

                isConnected = true;
            }
            catch (Exception)
            {
                DisposeSocket();
                throw;
            }
        }
コード例 #17
0
ファイル: MobileTcpClient.cs プロジェクト: Grawl/hubbl
 public MobileTcpClient(UsersService usersService, TcpSocketClient client)
 {
     _usersService = usersService;
     _client = client;
 }
コード例 #18
0
        public void Connect()
        {
            this.socket = new TcpSocketClient();

            // connection is executed synchronously
            this.socket.ConnectAsync(this.remoteHostName,
                this.remotePort,
                this.sslProtocol != MqttSslProtocols.None).Wait();
        }
コード例 #19
0
 private void SetSocket(TcpSocketClient socket)
 {
     this.socket = socket;
 }
コード例 #20
0
        private void DisposeSocket()
        {
            if (this.socket != null)
            {
                if (isConnected)
                {
                    isConnected = false;
                    Disconnected?.Invoke(this);
                }

                this.socket.Dispose();
                this.socket = null;
            }
        }
コード例 #21
0
ファイル: TcpClient.cs プロジェクト: pousqie/MessageRouter
 private TcpClient(IUsersService usersService, TcpSocketClient client)
 {
     _usersService = usersService;
     _client = client;
 }
コード例 #22
0
        public async Task TcpSocketClient_ShouldSendReceiveDataSimultaneously(int bufferSize)
        {
            var port = PortGranter.GrantPort();

            TcpSocketListener listener = null;
            TcpSocketClient socket1 = null;

            // get both ends of a connected socket, with or without buffer
            if (bufferSize != -1)
            {
                listener = new TcpSocketListener(bufferSize);
                socket1 = new TcpSocketClient(bufferSize);
            }
            else
            {
                listener = new TcpSocketListener();
                socket1 = new TcpSocketClient();
            }

            var tcs = new TaskCompletionSource<ITcpSocketClient>();
            
            await listener.StartListeningAsync(port);
            listener.ConnectionReceived += (sender, args) => tcs.SetResult(args.SocketClient);

            await socket1.ConnectAsync("127.0.0.1", port);

            var socket2 = await tcs.Task;
            await listener.StopListeningAsync();

            // socket1 is the socket from the client end
            // socket2 is the socket from the server end

            // for five seconds, send and receive the data 
            var sentToSocket1 = new List<byte>();
            var sentToSocket2 = new List<byte>();
            var recvdBySocket1 = new List<byte>();
            var recvdBySocket2 = new List<byte>();

            // send random data and keep track of it
            // also keep track of what is received
            Func<ITcpSocketClient, List<byte>, List<byte>, CancellationToken, Task> sendAndReceive =
                (socket, sent, recvd, token) =>
                {
                    var r = new Random(socket.GetHashCode());
                    var send = Task.Run(async () =>
                    {
                        var buf = new byte[1000];
                        while (!token.IsCancellationRequested)
                        {
                            r.NextBytes(buf);
                            sent.AddRange(buf);
                            await socket.WriteStream.WriteAsync(buf, 0, buf.Length, token);
                            await socket.WriteStream.FlushAsync(token);
                        }
                    });

                    var recv = Task.Run(async () =>
                    {
                        var buf = new byte[1000];
                        while (!token.IsCancellationRequested)
                        {
                            var len = await socket.ReadStream.ReadAsync(buf, 0, buf.Length, token);
                            recvd.AddRange(buf.Take(len));
                        }
                    });

                    var innerTcs = new TaskCompletionSource<bool>();
                    token.Register(() => innerTcs.SetResult(true));

                    return innerTcs.Task;
                };

            // let the sockets run for 2.5 seconds
            var socketRunners =
                Task.WhenAll(
                    Task.Run(() => sendAndReceive(socket1, sentToSocket2, recvdBySocket1, new CancellationTokenSource(TimeSpan.FromSeconds(2.5)).Token).ContinueWith(t=> Debug.WriteLine($"Socket 1 task completed: {t}"))),
                    Task.Run(() => sendAndReceive(socket2, sentToSocket1, recvdBySocket2, new CancellationTokenSource(TimeSpan.FromSeconds(2.5)).Token).ContinueWith(t => Debug.WriteLine($"Socket 2 task completed: {t}")))
                    );

            await socketRunners;

            Debug.WriteLine("Sent to S1:{0}, Recvd by S1:{1}", sentToSocket1.Count, recvdBySocket1.Count);
            Debug.WriteLine("Sent to S2:{0}, Recvd by S2:{1}", sentToSocket2.Count, recvdBySocket2.Count);

            // zip will join up to the lowest index of both lists (must be recvd)
            // it's ok if recvd is shorter than sent because we cancel abruptly,
            // but we want to be sure that everything that was received matches 
            // everything that sent, and that we did both send and receive.

            var socket1Errors =
                Enumerable.Zip(recvdBySocket1, sentToSocket1,
                            (r, s) => s == r)
                        .Count(b => !b);

            var socket2Errors =
                Enumerable.Zip(recvdBySocket2, 
                                sentToSocket2,
                            (r, s) => s == r)
                        .Count(b => !b);
            
            var max = new[] {recvdBySocket1.Count, recvdBySocket2.Count, sentToSocket1.Count, sentToSocket2.Count}.Max();
            Func<List<byte>, int, string> getValueOrStars =
                (bytes, i) => bytes.Count > i ? ((int) bytes[i]).ToString().PadLeft(3, '0') : "***";

            var rows =
                Enumerable.Range(0, max - 1)
                    .Select(i =>
                    {
                        var sTo1 = getValueOrStars(sentToSocket1, i);
                        var rBy1 = getValueOrStars(recvdBySocket1, i);
                        var sTo2 = getValueOrStars(sentToSocket2, i);
                        var rBy2 = getValueOrStars(recvdBySocket2, i);

                        return new { Index = i, SentTo1 = sTo1, ReceivedBy1 = rBy1, SentTo2 = sTo2, ReceivedBy2 = rBy2};
                    })
                    .Where(r => (r.SentTo1 != r.ReceivedBy1 && r.ReceivedBy1 != "***") || (r.SentTo2 != r.ReceivedBy2 && r.ReceivedBy2 != "***"))
                    .Select(r=> $"{r.Index}: \t{r.SentTo1}\t{r.ReceivedBy1}\t{r.SentTo2}\t{r.ReceivedBy2}\t")
                    .Take(1000);
            
            Func<IEnumerable<byte>, string> show = bs => $"[ {String.Join(", ", bs.Take(5).Select(b => (int) b))} ]";

            if (socket1Errors > 0 || socket2Errors > 0)
            {
                Assert.True(socket1Errors == 0,
                    $"Socket1 received {socket1Errors} byte/s that did not match what was sent to it{Environment.NewLine}{String.Join(Environment.NewLine, rows)}");
                Assert.True(socket2Errors == 0,
                    $"Socket2 received {socket2Errors} byte/s that did not match what was sent to it{Environment.NewLine}{String.Join(Environment.NewLine, rows)}");
            }
            // eww, but does the job we need
            Assert.True(recvdBySocket1.Count > 5000, String.Format("Socket 1 received data count was less than 5000 : {0}", recvdBySocket1.Count));
            Assert.True(recvdBySocket2.Count > 5000, String.Format("Socket 2 received data count was less than 5000 : {0}", recvdBySocket2.Count));

            await socket1.DisconnectAsync();
            await socket2.DisconnectAsync();
        }
コード例 #23
0
        public Task TcpSocketClient_Connect_ShouldCancelByCancellationToken()
        {
            var sut = new TcpSocketClient();
            
            var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
            var ct = cts.Token;

            // let's just hope no one's home :)
            return Assert.ThrowsAsync<OperationCanceledException>(()=> sut.ConnectAsync("99.99.99.99", 51234, cancellationToken: cts.Token));
        }
コード例 #24
0
        [InlineData(1000)] // yes buffered stream
        public async Task TcpSocketClient_ShouldBeAbleToDisconnectThenReconnect(int bufferSize)
        {
            TcpSocketClient sut = null;

            var port = PortGranter.GrantPort();
            var listener = new TcpSocketListener();
            await listener.StartListeningAsync(port);

            if (bufferSize != -1)
                sut = new TcpSocketClient(bufferSize);
            else
                sut = new TcpSocketClient();

            await sut.ConnectAsync("127.0.0.1", port);
            await sut.DisconnectAsync();

            await sut.ConnectAsync("127.0.0.1", port); 
            await sut.DisconnectAsync();

            await listener.StopListeningAsync();
        }
コード例 #25
0
 private static async Task SendAndReceiveAck(TcpSocketClient socket, uint sentAck, uint expectedAck)
 {
     await socket.WriteStream.WriteInt32Async((int)sentAck);
     await socket.WriteStream.FlushAsync();
     var ack = (uint)await socket.ReadStream.ReadInt32Async();
     if (ack != expectedAck)
         throw new SimpleSocketException("Invalid ack");
 }
コード例 #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TcpConnection" /> class.
 /// </summary>
 /// <param name="useSsl">if set to <c>true</c> the connection is secured using SSL.</param>
 public TcpConnection(bool useSsl)
 {
     _isSecure = useSsl;
     _client = new TcpSocketClient();
 }
コード例 #27
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="socket">Socket opened with the client</param>
 public MqttNetworkChannel(TcpSocketClient socket)
 {
     this.socket = socket;
     this.sslProtocol = MqttSslProtocols.None;
 }
コード例 #28
0
 public void TcpSocketClient_Constructor_ShouldSucceed()
 {
     // just checking bait and switch is set up
     var socket = new TcpSocketClient();
     Assert.True(true);
 }
コード例 #29
0
ファイル: Server.cs プロジェクト: fcin/RemindMe
 private int ReadByte(TcpSocketClient client)
 {
     return Task.Run(() => client.ReadStream.ReadByte()).Result;
 }
コード例 #30
0
        /// <summary>
        /// Connects to the Logentries API Server.
        /// </summary>
        public void Connect()
        {
            if (_useHttpPut)
            {
                _httpClient = new HttpClient();
            }
            else
            {
                _socketClient = new TcpSocketClient();

                var task = _socketClient.ConnectAsync(_url, _tcpPort, _useSsl);

                task.Wait(new TimeSpan(0, 0, 30));
            }
        }