public void Setup()
        {
            _endpoint = new IPEndPoint(IPAddress.Loopback, 45982);
            _client = new Socket(_endpoint.AddressFamily, SocketType.Stream, ProtocolType.IP);

            _wrapper = new SocketWrapper(_client);
            _wrapper.Bind(_endpoint);
            _wrapper.Listen(100);
        }
Пример #2
0
        public Connection(int connectionId, Manager manager, Socket client, IPEndPoint serverDestination)
        {
            _connectionId = connectionId;
            _manager = manager;
            Client = new SocketWrapper(client);
            _serverDestination = serverDestination;

            _packetProcessor = new PacketProcessor(_connectionId);

            Client.DataReceivedEvent += ClientOnDataReceivedEvent;
            Client.Receive();
        }
Пример #3
0
        public void Setup()
        {
            _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            _endpoint = new IPEndPoint(IPAddress.Loopback, 45982);
            _listener.Bind(_endpoint);
            _listener.Listen(10);

            _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            ThreadPool.QueueUserWorkItem(x => {
                Thread.Sleep(100);
                _client.Connect(_endpoint);
            });
            _socket = _listener.Accept();

            _wrapper = new SocketWrapper(_socket);
        }
Пример #4
0
        public void Start()
        {
            if (!_started)
            {
                Console.WriteLine($"[{_connectionId}][Connection#Start]: Connecting...");

                _started = true;

                Server = new SocketWrapper(new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp));
                Server.Socket.BeginConnect(_serverDestination, DestinationConnectCallback, null);
            }
            else
            {
                Console.WriteLine($"[{_connectionId}][Connection#Start]: Already started.");
            }
        }
 public async void AddSocket(SocketWrapper socket)
 {
     await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         lock (thisLock)
         {
             ConnectedSockets.Items.Add(socket);
         }
     });
 }
Пример #6
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (serversRunning != 0)
            {
                return;
            }

            Interlocked.Increment(ref serversRunning);

            // Server start
            serverTaskMain = new Task(() =>
                {
                    // Server setup
                    SocketWrapper[] listenSocketArr = new SocketWrapper[1];
                    uint q = SocketsWrapper.Socket(AddressFamily.QCC_AF_INET, SocketType.QCC_SOCK_STREAM, listenSocketArr);
                    SocketWrapper listenSocket = listenSocketArr[0];

                    q = listenSocket.Bind("0.0.0.0", Port);
                    q = listenSocket.Listen(10);

                    for (int s = 0; s < Servers; s++)
                    {
                        if (s != 0)
                        {
                            Interlocked.Increment(ref serversRunning);
                        }
                        _serverTasks[s] = new Task(() =>
                            {
                                string[] remoteAddr = new string[1];
                                int[] remotePort = new int[1];
                                SocketWrapper[] newSocketArr = new SocketWrapper[1];

                                while (listenSocket.Accept(remoteAddr, remotePort, newSocketArr) == 0)
                                {
                                    int bytesLeft = PatternLength;
                                    int byteCount = 0;
                                    using (SocketWrapper newSocket = newSocketArr[0])
                                    {
                                        int[] sentArr = new int[1];
                                        while (bytesLeft != 0)
                                        {
                                            byte[] tempBytes = new byte[Math.Min(bytesLeft, MaxSendBuffer)];
                                            for (int i = 0; i < tempBytes.Length; i++)
                                            {
                                                tempBytes[i] = (byte)((i + byteCount) % 256);
                                            }
                                            q = newSocket.Send(tempBytes, tempBytes.Length, sentArr);
                                            if (q != 0)
                                            {                                                
                                                break;
                                            }
                                            byteCount += sentArr[0];
                                            bytesLeft -= sentArr[0];
                                        }
                                    }
                                }

                                Interlocked.Decrement(ref serversRunning);
                            });
                        _serverTasks[s].Start();
                    }
                });
            serverTaskMain.Start();
        }
Пример #7
0
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            if (clientsRunning != 0)
            {
                return;
            }

            Interlocked.Increment(ref clientsRunning);

            // Client start
            for (int c = 0; c < Clients; c++)
            {
                if (c != 0)
                {
                    Interlocked.Increment(ref clientsRunning);
                }

                _clientTasks[c] = new Task(() =>
                {
                    while (true)
                    {
                        SocketWrapper[] clientSocketArr = new SocketWrapper[1];
                        SocketsWrapper.Socket(AddressFamily.QCC_AF_INET, SocketType.QCC_SOCK_STREAM, clientSocketArr);
                        using (SocketWrapper clientSocket = clientSocketArr[0])
                        {
                            uint q = clientSocket.Connect(Address, Port);
                            byte[] tempBytes = new byte[PatternLength];
                            int[] receivedArr = new int[1];

                            int bytesLeft = tempBytes.Length;
                            int byteCount = 0;
                            bool success = true;
                            do
                            {
                                q = clientSocket.Recv(tempBytes, tempBytes.Length, receivedArr);
                                if (q != 0)
                                {
                                    success = false;
                                    break;
                                }

                                for (int i = 0; i < receivedArr[0]; i++)
                                {
                                    if (tempBytes[i] != ((i + byteCount) % 256))
                                    {
                                        success = false;
                                        break;
                                    }
                                }

                                byteCount += receivedArr[0];
                                bytesLeft -= receivedArr[0];
                            }
                            while (bytesLeft > 0);

                            // Update the count
                            Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                                {
                                    if (success)
                                    {
                                        successCount.Text = (++_successCount).ToString();
                                    }
                                    else
                                    {
                                        failCount.Text = (++_failCount).ToString();
                                    }
                                }); 
                        }
                    }

                    Interlocked.Decrement(ref clientsRunning);
                });
                _clientTasks[c].Start();
            }
        }
 public void AddSocket(SocketWrapper socket)
 {
     // Update UI to add this to list
     if (scenario5 != null)
     {
         scenario5.AddSocket(socket);
     }
 }
            public void AddStreamSocketInternal(StreamSocket socket)
            {
                SocketWrapper socketWrapper = new SocketWrapper(manager, socket, null);
                
                // Start receiving messages recursively
                var rcv = socketWrapper.ReceiveMessageAsync();

                socketList.Add(socketWrapper);
                // Update manager so UI can add to list
                manager.AddSocket(socketWrapper);
            }
            // This will fire when the connected peer attempts to open a port for this connection
            // The peer should start a stream socket listener (for TCP)
            private async void OnRemotePortAdded(WiFiDirectServiceSession sender, WiFiDirectServiceRemotePortAddedEventArgs args)
            {
                try
                {
                    ThrowIfDisposed();

                    var endpointPairCollection = args.EndpointPairs;
                    var protocol = args.Protocol;
                    if (endpointPairCollection.Count == 0)
                    {
                        manager.NotifyUser("No endpoint pairs for remote port added event", NotifyType.ErrorMessage);
                        return;
                    }

                    manager.NotifyUser(String.Format("{0} Port {1} Added by remote peer",
                        (protocol == WiFiDirectServiceIPProtocol.Tcp) ? "TCP" : ((protocol == WiFiDirectServiceIPProtocol.Udp) ? "UDP" : "???"),
                        endpointPairCollection[0].RemoteServiceName
                        ),
                        NotifyType.StatusMessage
                        );

                    SocketWrapper socketWrapper = null;

                    if (args.Protocol == WiFiDirectServiceIPProtocol.Tcp)
                    {
                        // Connect to the stream socket listener
                        StreamSocket streamSocket = new StreamSocket();
                        socketWrapper = new SocketWrapper(manager, streamSocket, null);

                        manager.NotifyUser("Connecting to stream socket...", NotifyType.StatusMessage);
                        await streamSocket.ConnectAsync(endpointPairCollection[0]);
                        // Start receiving messages recursively
                        var rcv = socketWrapper.ReceiveMessageAsync();
                        manager.NotifyUser("Stream socket connected", NotifyType.StatusMessage);
                    }
                    else if (args.Protocol == WiFiDirectServiceIPProtocol.Udp)
                    {
                        // Connect a socket over UDP
                        DatagramSocket datagramSocket = new DatagramSocket();
                        socketWrapper = new SocketWrapper(manager, null, datagramSocket);

                        manager.NotifyUser("Connecting to datagram socket...", NotifyType.StatusMessage);
                        await datagramSocket.ConnectAsync(endpointPairCollection[0]);
                        manager.NotifyUser("Datagram socket connected", NotifyType.StatusMessage);
                    }
                    else
                    {
                        manager.NotifyUser("Bad protocol for remote port added event", NotifyType.ErrorMessage);
                        return;
                    }

                    socketList.Add(socketWrapper);
                    // Update manager so UI can add to list
                    manager.AddSocket(socketWrapper);
                }
                catch (Exception ex)
                {
                    manager.NotifyUser("OnRemotePortAdded Failed: " + ex.Message, NotifyType.ErrorMessage);
                }
            }
            public async void AddDatagramSocketAsync(UInt16 port)
            {
                ThrowIfDisposed();

                manager.NotifyUser("Adding stream socket listener for UDP port " + port, NotifyType.StatusMessage);

                var endpointPairCollection = session.GetConnectionEndpointPairs();
                
                DatagramSocket socket = new DatagramSocket();
                SocketWrapper socketWrapper = new SocketWrapper(manager, null, socket);

                socketList.Add(socketWrapper);

                // Bind UDP socket for receiving messages (peer should call connect and send messages to this socket)
                manager.NotifyUser("BindEndpointAsync...", NotifyType.StatusMessage);
                await socket.BindEndpointAsync(endpointPairCollection[0].LocalHostName, Convert.ToString(port, CultureInfo.InvariantCulture));
                manager.NotifyUser("BindEndpointAsync Done", NotifyType.StatusMessage);

                manager.NotifyUser("AddDatagramSocketAsync...", NotifyType.StatusMessage);
                await session.AddDatagramSocketAsync(socket);
                manager.NotifyUser("AddDatagramSocketAsync Done", NotifyType.StatusMessage);
                
                // Update manager so UI can add to list
                manager.AddSocket(socketWrapper);
            }