Last active
March 3, 2020 09:30
-
-
Save oleksabor/5f9240d07ac0d66251325e45275c20db to your computer and use it in GitHub Desktop.
System.Net.Sockets.Socket.ReceiveFromAsync sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net; | |
using System.Net.Sockets; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace ClassLibraryTCP | |
{ | |
[TestClass] | |
public class Class1 | |
{ | |
public async Task SendTo1() | |
{ | |
IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); | |
IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], 11000); | |
using (Socket s = new Socket(endPoint.Address.AddressFamily, | |
SocketType.Stream, | |
ProtocolType.Tcp)) | |
{ | |
s.Connect(endPoint); | |
byte[] msg = Encoding.ASCII.GetBytes("This is a test"); | |
Console.WriteLine("Sending data."); | |
var res = await s.SendToAsync(new ArraySegment<byte>(msg), SocketFlags.None, endPoint); | |
var response = new byte[256]; | |
EndPoint receiver = endPoint; | |
var args = new SocketAsyncEventArgs | |
{ | |
RemoteEndPoint = receiver, | |
}; | |
args.SetBuffer(response, 0, 256); | |
args.Completed += receive_Completed; | |
var pending = s.ReceiveFromAsync(args); | |
if (!pending) | |
receive_Completed(s, args); // receive_Completed will not be called if not pending so must be called manually | |
s.Close(); | |
} | |
} | |
private void receive_Completed(object sender, SocketAsyncEventArgs e) | |
{ | |
Console.WriteLine("received {0} bytes from server", e.BytesTransferred); | |
} | |
public void ReceiveFrom2(CancellationToken cnclToken) | |
{ | |
IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); | |
IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], 11000); | |
using (Socket s = new Socket(endPoint.Address.AddressFamily, | |
SocketType.Stream, | |
ProtocolType.Tcp) | |
) | |
{ | |
// Creates an IpEndPoint to capture the identity of the sending host. | |
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); | |
EndPoint senderRemote = (EndPoint)sender; | |
// Binding is required with ReceiveFrom calls. | |
s.Bind(endPoint); | |
s.Listen(100); | |
var res = s.BeginAccept(OnClientConnected, s); | |
Console.WriteLine("waiting for incoming connection"); | |
while (!cnclToken.IsCancellationRequested) | |
Thread.Sleep(200); | |
} | |
} | |
void OnClientConnected(IAsyncResult asyncRes) | |
{ | |
var client = (Socket)asyncRes.AsyncState; | |
byte[] buf = null; | |
var s = client.EndAccept(out buf, asyncRes); | |
EndPoint remoteEP = s.RemoteEndPoint; | |
Console.WriteLine("has got {0} bytes from client", buf.Length); | |
var reply = new byte[99]; | |
var sent = s.SendTo(reply, remoteEP); | |
Console.WriteLine("sent {0} bytes to client", sent); | |
} | |
[TestMethod] | |
public async Task Test() | |
{ | |
var cncl = new CancellationTokenSource(); | |
var t = Task.Run(() => ReceiveFrom2(cncl.Token)); | |
while (t.Status != TaskStatus.Running) | |
Thread.Sleep(200); | |
await SendTo1(); | |
cncl.Cancel(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment