private void OnConnected(TcpSocketConnect data) { if (data.Status == SocketStatus.OK) { socket.Send(outgoing, OnSent); } else { Console.WriteLine("OnConnected"); socket.Dispose(); } }
/// <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(); }
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); }
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)); }
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)); } } }
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(); } }
public void TcpSend(byte[] buff) { if (tcpRuning) { tcpClient.Send(buff); } }
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); } }
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)); } } }
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(); } }); }
/// <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); } }
// 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()); }
/// <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); } }
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()); }
// [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(); }
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); } }
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)); } }
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)); } } }
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); }
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)); } }
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); }
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(); } }
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(); }
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"); }
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(); } }
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); } }
private unsafe ValueTask <byte> SendToSocket(MemoryHandle dataHandle, ushort len, bool more) { return(_tun.executeLwipTask(() => _socket.Send((ulong)dataHandle.Pointer, len, more))); }