Send() 공개 메소드

public Send ( string str ) : void
str string
리턴 void
예제 #1
0
 private void OnConnected(TcpSocketConnect data)
 {
     if (data.Status == SocketStatus.OK)
     {
         socket.Send(outgoing, OnSent);
     }
     else
     {
         Console.WriteLine("OnConnected");
         socket.Dispose();
     }
 }
예제 #2
0
        /// <deprecated>
        /// Not used. For reference only.
        /// </deprecated>
        private async void StartPolling1()
        {
            while (true)
            {
                var readResult = await pipeReader.ReadAsync().ConfigureAwait(false);

                ReadOnlySequence <byte> buffer   = readResult.Buffer;
                SequencePosition?       position = buffer.Start;
                var remainingBytes = buffer.Length;
                var writeResult    = (byte)0;
                while (remainingBytes > 0)
                {
                    while (localStackByteCount == 0)
                    {
                        await _tun.executeLwipTask(() => _socket.Output());

                        await localStackBufLock.WaitAsync().ConfigureAwait(false);
                    }
                    var bytesToWriteCount = Math.Min(remainingBytes, localStackByteCount);
                    var chunk             = buffer.Slice(position.Value, bytesToWriteCount);
                    var arr  = chunk.ToArray();
                    var more = remainingBytes != bytesToWriteCount;
                    writeResult = await _tun.executeLwipTask(() => _socket.Send(arr, more));

                    if (writeResult != 0)
                    {
                        OnError?.Invoke(this, writeResult);
                        pipeReader.Complete();
                        return;
                    }
                    remainingBytes -= bytesToWriteCount;
                    position        = buffer.GetPosition(bytesToWriteCount, position.Value);
                    Interlocked.Add(ref localStackByteCount, (int)-bytesToWriteCount);
                }
                pipeReader.AdvanceTo(position.Value, position.Value);
                await _tun.executeLwipTask(() => _socket.Output());

                if (readResult.IsCanceled || readResult.IsCompleted || writeResult != 0)
                {
                    break;
                }
            }
            pipeReader.Complete();
            await _tun.executeLwipTask(() => _socket.Close());

            Debug.WriteLine($"{TcpSocket.ConnectionCount()} connections now");
            LocalDisconnected = true;
            OnFinished(this);
            CheckShutdown();
        }
예제 #3
0
        public void TestEvent()
        {
            bool isOnConnecting   = false;
            bool isOnConnected    = false;
            bool isOnDisconnected = false;
            bool isOnSend         = false;
            bool isOnReceive      = false;

            TcpSocket tcp = new TcpSocket();

            tcp.OnConnecting    += () => { isOnConnecting = true; };
            tcp.OnConnected     += () => { isOnConnected = true; };
            tcp.OnDisconnected  += () => { isOnDisconnected = true; };
            tcp.OnSocketSend    += (x) => { isOnSend = true; };
            tcp.OnSocketReceive += (x) => { isOnReceive = true; };

            tcp.Connect(Common.GetIpEndPoint());
            Assert.IsTrue(isOnConnecting);

            Common.WaitTrue(ref isOnConnected);
            Assert.IsTrue(isOnConnected);

            tcp.Send(new byte[10]);
            Common.WaitTrue(ref isOnSend);
            Assert.IsTrue(isOnSend);

            Common.WaitTrue(ref isOnReceive);
            Assert.IsTrue(isOnReceive);

            tcp.DisConnect();
            Assert.IsTrue(isOnDisconnected);
        }
예제 #4
0
        public async Task <string> Send(IPEndPoint endpoint, string message)
        {
            int progress = 0;

            byte[] output = new byte[message.Length];
            byte[] bytes  = Encoding.ASCII.GetBytes(message);

            using (TcpSocket socket = factory.Tcp())
            {
                socket.Bind();

                TcpSocketConnect connected = await socket.Connect(endpoint);

                TcpSocketSend sent = await socket.Send(bytes);

                while (progress < output.Length)
                {
                    SocketBuffer     buffer   = new SocketBuffer(output, progress);
                    TcpSocketReceive received = await socket.Receive(buffer);

                    if (received.Count == 0)
                    {
                        break;
                    }

                    progress += received.Count;
                }
            }

            return(Encoding.ASCII.GetString(output));
        }
예제 #5
0
        public async Task CanReceiveDataUsingTasksToHostedEchoServer()
        {
            string request = "GET /index.html HTTP/1.1\r\nHost: www.example.com\r\n\r\n";

            byte[] input  = Encoding.ASCII.GetBytes(request);
            byte[] output = new byte[input.Length];

            using (CompletionThread worker = new CompletionThread())
            {
                SocketFactory factory = new SocketFactory(worker);
                TcpSocket     socket  = factory.Tcp();

                using (EchoServer server = new EchoServer(factory))
                {
                    socket.Bind();
                    worker.Start();
                    server.Start();

                    await socket.Connect(server.Endpoint);

                    await socket.Send(input);

                    await socket.Receive(output);

                    Assert.That(input, Is.EqualTo(output));
                }
            }
        }
예제 #6
0
        public void RejectHugePacket()
        {
            using (TcpListener listener = new TcpListener(1024))
            {
                listener.Blocking = true;
                listener.Listen(PORT);

                TcpSocket clientSock       = new TcpSocket();
                var       connectionResult = clientSock.ConnectAsync("localhost", PORT).Result;

                var status = listener.Accept(out TcpSocket serverSock);
                Assert.AreEqual(SocketStatus.Done, status);

                var largePacket = new NetPacket();
                largePacket.WriteBytes(new byte[8192], true);

                while (clientSock.Send(largePacket) != SocketStatus.Done)
                {
                    ;
                }

                Assert.AreEqual(SocketStatus.Disconnected, serverSock.Receive(largePacket));

                Assert.IsFalse(serverSock.Connected);

                clientSock.Dispose();
                serverSock.Dispose();
                largePacket.Dispose();
            }
        }
예제 #7
0
 public void TcpSend(byte[] buff)
 {
     if (tcpRuning)
     {
         tcpClient.Send(buff);
     }
 }
예제 #8
0
파일: SendTests.cs 프로젝트: vnvizitiu/leak
        public void CanSendDataUsingCallbackToExampleSite()
        {
            TimeSpan         timeout = TimeSpan.FromSeconds(2);
            ManualResetEvent check   = new ManualResetEvent(false);

            IPAddress[] addresses = Dns.GetHostAddresses("www.example.com");
            IPEndPoint  endpoint  = new IPEndPoint(addresses[0], 80);

            using (CompletionThread worker = new CompletionThread())
            {
                SocketFactory factory = new SocketFactory(worker);
                TcpSocket     socket  = factory.Tcp();

                socket.Bind();
                worker.Start();

                TcpSocketSendCallback onSent = result =>
                {
                    check.Set();
                };

                TcpSocketConnectCallback onConnected = result =>
                {
                    string request = "GET /index.html HTTP/1.1\r\nHost: www.example.com\r\n\r\n";
                    byte[] data    = Encoding.ASCII.GetBytes(request);

                    socket.Send(data, onSent);
                };

                socket.Connect(endpoint, onConnected);
                bool completed = check.WaitOne(timeout);

                Assert.That(completed, Is.True);
            }
        }
예제 #9
0
파일: SendTests.cs 프로젝트: vnvizitiu/leak
        public async Task CanHandleTerminatedStream()
        {
            IPAddress  localhost = IPAddress.Loopback;
            IPEndPoint endpoint  = new IPEndPoint(localhost, 1234);

            using (CompletionThread worker = new CompletionThread())
            {
                SocketFactory factory = new SocketFactory(worker);

                using (TcpSocket server = factory.Tcp())
                    using (TcpSocket socket = factory.Tcp())
                    {
                        socket.Bind();
                        worker.Start();

                        server.Bind(endpoint.Port);
                        server.Listen(1);

                        Task <TcpSocketAccept> acceptable = server.Accept();
                        await socket.Connect(endpoint);

                        TcpSocketAccept accepted = await acceptable;
                        accepted.Connection.Dispose();

                        byte[]        buffer = new byte[10];
                        TcpSocketSend sent   = await socket.Send(buffer);

                        Assert.That(sent.Status, Is.EqualTo(SocketStatus.OK));
                    }
            }
        }
예제 #10
0
        internal TunSocketAdapter(TcpSocket socket, TunInterface tun)
        {
            _socket = socket;
            _tun    = tun;

            socket.DataReceived += Socket_DataReceived;
            socket.DataSent     += Socket_DataSent;
            socket.SocketError  += Socket_SocketError;

            sendBufferTask = Task.Run(() =>
            {
                while (true)
                {
                    _tun.executeLwipTask(() =>
                    {
                        while (sendBuffers.TryPeek(out IBuffer buf))
                        {
                            if (_socket.Send(buf.ToArray()) == 0)
                            {
                                sendBuffers.TryDequeue(out buf);
                            }
                            else
                            {
                                break;
                            }
                        }
                    });
                    checkSendBufferHandle.Reset();
                    checkSendBufferHandle.WaitOne();
                }
            });
        }
예제 #11
0
 /// <summary>
 /// Send the message to the client.
 ///
 /// /!\ USED ONLY IN NETWORKIO WORKERS /!\
 /// </summary>
 /// <param name="aData">The data to send to the client.</param>
 public void _Send(ref Byte[] aData)
 {
     lock (mCipher)
     {
         mCipher.Encrypt(ref aData, aData.Length);
         mSocket.Send(aData);
     }
 }
예제 #12
0
    // Sends a message to the Sender that a Kinect frame was received.
    public void Send(int frameId)
    {
        int packetSize = 5;
        var ms         = new MemoryStream();

        ms.Write(BitConverter.GetBytes(packetSize), 0, 4);
        ms.WriteByte(0);
        ms.Write(BitConverter.GetBytes(frameId), 0, 4);
        socket.Send(ms.ToArray());
    }
예제 #13
0
        /// <summary>
        /// Send the message to the client.
        /// </summary>
        /// <param name="aMsg">The message to send to the client.</param>
        public void Send(Msg aMsg)
        {
            Byte[] msg = (Byte[])aMsg;
            Program.NetworkMonitor.Send(msg.Length);

            lock (mCipher)
            {
                mCipher.Encrypt(ref msg, msg.Length);
                mSocket.Send(msg);
            }
        }
예제 #14
0
    public void SendViewerScene(ViewerScene viewerScene)
    {
        var viewerSceneJson  = JsonUtility.ToJson(viewerScene);
        var viewerSceneBytes = Encoding.ASCII.GetBytes(viewerSceneJson);

        var ms = new MemoryStream();

        ms.Write(BitConverter.GetBytes(viewerSceneBytes.Length), 0, 4);
        ms.Write(viewerSceneBytes, 0, viewerSceneBytes.Length);
        tcpSocket.Send(ms.ToArray());
    }
    public void SendViewerState(List <ReceiverState> receiverStates)
    {
        var viewerState      = new ViewerState(UserId, receiverStates);
        var viewerStateJson  = JsonUtility.ToJson(viewerState);
        var viewerStateBytes = Encoding.ASCII.GetBytes(viewerStateJson);

        var ms = new MemoryStream();

        ms.Write(BitConverter.GetBytes(viewerStateBytes.Length), 0, 4);
        ms.Write(viewerStateBytes, 0, viewerStateBytes.Length);
        tcpSocket.Send(ms.ToArray());
    }
예제 #16
0
        // [Test]
        public void StressTest()
        {
            TcpListener listener = new TcpListener();

            listener.Listen(PORT);

            TcpSocket clientSock       = new TcpSocket();
            var       connectionResult = clientSock.ConnectAsync("localhost", PORT).Result;

            var status = listener.Accept(out TcpSocket serverSock);

            for (int i = 0; i < 1000000; i++)
            {
                NetPacket packet = new NetPacket();

                var messageTo = Guid.NewGuid().ToString();
                packet.WriteString(messageTo);
                while (serverSock.Send(packet) != SocketStatus.Done)
                {
                    ;
                }

                packet.Clear();

                while (clientSock.Receive(packet) != SocketStatus.Done)
                {
                    ;
                }

                Assert.AreEqual(messageTo, packet.ReadString());
                packet.ResetWrite();

                packet.WriteString($"Message with code {messageTo} received.");
                while (clientSock.Send(packet) != SocketStatus.Done)
                {
                    ;
                }

                packet.Clear();

                while (serverSock.Receive(packet) != SocketStatus.Done)
                {
                    ;
                }

                packet.Dispose();
            }

            listener.Dispose();
            clientSock.Dispose();
            serverSock.Dispose();
        }
예제 #17
0
        internal void Tap(Point location)
        {
            if (minitouchSocket == null || !minitouchSocket.Connected)
            {
                Install();
            }
            int    x        = (int)Math.Round(rnd.Next(location.X - 10, location.X + 10) * Scale);
            int    y        = (int)Math.Round(rnd.Next(location.Y - 10, location.Y - 10) * Scale);
            int    pressure = (int)Math.Round(rnd.Next(50, 200) * Scale);
            string cmd      = $"d 0 {x} {y} {pressure}\nc\nu 0\nc\n";

            byte[] bytes = AdbClient.Encoding.GetBytes(cmd);
            try
            {
                minitouchSocket.Send(bytes, 0, bytes.Length, SocketFlags.None);
            }
            catch
            {
                Install();
                Thread.Sleep(3000);
                Tap(location);
            }
        }
예제 #18
0
 static public int Send(IntPtr l)
 {
     try {
         TcpSocket     self = (TcpSocket)checkSelf(l);
         System.String a1;
         checkType(l, 2, out a1);
         self.Send(a1);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
예제 #19
0
파일: SendTests.cs 프로젝트: vnvizitiu/leak
        public async Task CanHandleNotBoundSocket()
        {
            using (CompletionThread worker = new CompletionThread())
            {
                SocketFactory factory = new SocketFactory(worker);

                using (TcpSocket socket = factory.Tcp())
                {
                    byte[]        buffer = new byte[10];
                    TcpSocketSend sent   = await socket.Send(buffer);

                    Assert.That(sent.Status, Is.Not.EqualTo(SocketStatus.OK));
                }
            }
        }
예제 #20
0
        public void TestSendReceive()
        {
            TcpSocket tcp = new TcpSocket();

            tcp.Connect(Common.GetIpEndPoint());
            Common.WaitConnect(tcp);
            int length = 0;

            tcp.OnSocketReceive += (x) =>
            {
                length = x.Length;
            };
            tcp.Send(new byte[10]);
            Common.WaitValue(ref length, 10);
            Assert.AreEqual(length, 10);
        }
예제 #21
0
        public void Send(NetworkOutgoingMessage message, Action callback)
        {
            if (listener.IsAvailable(identifier))
            {
                DataBlock    block  = new NetworkOutgoingBlock(memory.Data, offset, message.Length);
                SocketBuffer buffer = new SocketBuffer(memory.Data, offset, message.Length);

                message.ToBytes(block);
                encryptor?.Encrypt(memory.Data, offset, message.Length);

                offset += message.Length;
                parts.Add(offset);

                socket.Send(buffer, OnSent(callback));
            }
        }
예제 #22
0
        public void TestLargeMessage()
        {
            var tcp = new TcpSocket();

            tcp.Connect(Common.GetIpEndPoint());
            Common.WaitConnected(tcp);
            int length = 0;

            tcp.OnSocketReceive += (x) =>
            {
                length += x.Length;
            };
            tcp.Send(new byte[1 << 10]);
            Common.WaitValue(ref length, 1 << 10, 10000);
            tcp.DisConnect();
            Console.WriteLine(length);
            Assert.AreEqual(length, 1 << 10);
        }
예제 #23
0
        public void SendReceiveTest()
        {
            const string serverMessage = "HelloFromServer";
            const string clientMessage = "ResponseFromClient";

            using (TcpListener listener = new TcpListener())
            {
                listener.Blocking = true;
                listener.Listen(PORT);

                TcpSocket clientSock       = new TcpSocket();
                var       connectionResult = clientSock.ConnectAsync("localhost", PORT).Result;

                var status = listener.Accept(out TcpSocket serverSock);

                NetPacket packet       = new NetPacket();
                NetPacket clientPacket = new NetPacket();

                packet.WriteString(serverMessage);

                // Send message to client.
                Assert.AreEqual(SocketStatus.Done, serverSock.Send(packet));

                // Read message from server.
                Assert.AreEqual(SocketStatus.Done, clientSock.Receive(clientPacket));
                Assert.AreEqual(serverMessage, clientPacket.ReadString());

                // Send message back to server.
                clientPacket.Clear(SerializationMode.Writing);
                clientPacket.WriteString(clientMessage);
                Assert.AreEqual(SocketStatus.Done, clientSock.Send(clientPacket));

                // Read message from client.
                Assert.AreEqual(SocketStatus.Done, serverSock.Receive(packet));
                Assert.AreEqual(clientMessage, packet.ReadString());

                clientSock.Dispose();
                serverSock.Dispose();
                packet.Dispose();
                clientPacket.Dispose();
            }
        }
예제 #24
0
        public void LifecycleTest()
        {
            TcpSocket socket = new TcpSocket();

            Assert.IsFalse(socket.Connected);

            socket.Connect(new DnsEndPoint("www.google.com", 80));
            Assert.IsTrue(socket.Connected);

            byte[] data = Encoding.ASCII.GetBytes(@"GET / HTTP/1.1

");
            socket.Send(data, 0, data.Length, SocketFlags.None);

            byte[] responseData = new byte[128];
            socket.Receive(responseData, 0, SocketFlags.None);

            string response = Encoding.ASCII.GetString(responseData);

            socket.Dispose();
        }
예제 #25
0
        internal void Install()
        {
            string rndMiniTouch = Path.GetRandomFileName();

            try
            {
                controller.Execute("find /data/local/tmp/ -maxdepth 1 -type f -delete");
                controller.Push(minitouchpath, "/data/local/tmp/" + rndMiniTouch, 777);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Device Offline"))
                {
                    throw new Exception("Device Offline");
                }
            }

            bool successConnect = false;

            do
            {
                controller.CreateForward($"tcp:{minitouchPort}", "localabstract:minitouch");
                minitouchSocket = new TcpSocket();
                minitouchSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), minitouchPort));
                if (minitouchSocket.Connected)
                {
                    try
                    {
                        string cmd   = "d 0 0 0 100\nc\nu 0\nc\n";
                        byte[] bytes = AdbClient.Encoding.GetBytes(cmd);
                        minitouchSocket.Send(bytes, 0, bytes.Length, SocketFlags.None);
                        successConnect = true;
                    }
                    catch
                    {
                    }
                }
            }while (!successConnect);
            Console.Out.WriteLine("Minitouch install Success");
        }
예제 #26
0
        private async void OnAccepted(TcpSocketAccept data)
        {
            if (data.Status == SocketStatus.OK)
            {
                socket.Accept(OnAccepted);
            }

            if (data.Status == SocketStatus.OK)
            {
                TcpSocket other = data.Connection;
                byte[]    bytes = new byte[1024];

                while (true)
                {
                    TcpSocketReceive received = await other.Receive(bytes);

                    SocketBuffer buffer = new SocketBuffer(bytes, 0, received.Count);

                    if (received.Count == 0)
                    {
                        break;
                    }

                    if (received.Status != SocketStatus.OK)
                    {
                        break;
                    }

                    TcpSocketSend sent = await other.Send(buffer);

                    if (sent.Status != SocketStatus.OK)
                    {
                        break;
                    }
                }

                other.Dispose();
            }
        }
예제 #27
0
파일: SendTests.cs 프로젝트: vnvizitiu/leak
        public async Task CanSendDataUsingAsyncToExampleSite()
        {
            IPAddress[] addresses = Dns.GetHostAddresses("www.example.com");
            IPEndPoint  endpoint  = new IPEndPoint(addresses[0], 80);

            string request = "GET /index.html HTTP/1.1\r\nHost: www.example.com\r\n\r\n";

            byte[] data = Encoding.ASCII.GetBytes(request);

            using (CompletionThread worker = new CompletionThread())
            {
                SocketFactory factory = new SocketFactory(worker);
                TcpSocket     socket  = factory.Tcp();

                socket.Bind();
                worker.Start();

                await socket.Connect(endpoint);

                await socket.Send(data);
            }
        }
예제 #28
0
 private unsafe ValueTask <byte> SendToSocket(MemoryHandle dataHandle, ushort len, bool more)
 {
     return(_tun.executeLwipTask(() => _socket.Send((ulong)dataHandle.Pointer, len, more)));
 }