使用异步套接字多个套接字连接 [英] Multiple socket connections using asynchronous sockets

查看:191
本文介绍了使用异步套接字多个套接字连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code,使一个TCP套接字连接到多个端点这样:

 专用异步无效的button1_Click(对象发件人,EventArgs的发送)
    {
        VAR listofIps =新的List<串GT; {192.168.168.193,192.168.168.221};
        的foreach(在listofIps VAR IP)
        {
            IPEndPoint remoteEP =新IPEndPoint(IPAddress.Parse(IP),4001);
            客户端的Socket =新的Socket(AddressFamily.InterNetwork,
                                       SocketType.Stream,ProtocolType.Tcp);
            sockets.Add(客户端);
            等待client.ConnectTaskAsync(remoteEP);
            等待ReadAsync(客户端);
        }
    }    异步任务ReadAsync(插座S)
    {
        变参=新的SocketAsyncEventArgs();
        args.SetBuffer(新字节[1024],0,1024);        VAR awaitable =新SocketAwaitable(参数);        而(真)
        {
            等待s.ReceiveAsync(awaitable);
            INT读取动作= args.BytesTransferred;
            如果(读取动作< = 0)中断;            VAR数据=新ArraySegment<位>(args.Buffer,0,读取动作);
            AppendLog(RX:+ data.DumpHex());
        }
    }    公共静态字符串DumpHex(这ArraySegment<位>数据)
    {
        返回的string.join(,data.Select(二= GT; b.T​​oString(X2)));
    }    公共静态任务ConnectTaskAsync(此Socket插座,端点endpoint)
    {
        返回Task.Factory.FromAsync(socket.BeginConnect,socket.EndConnect,端点,NULL);
    }

不过,循环不会遍历传递,因为的await ReadAsync的第一个IP地址。

QN 1)如何修改此code,使其通过我的整个IP地址列表迭代没有等待为完全接收到的数据。难道我删除的await 从的await ReadAsync(客户端)?结果关键字
QN 2)如何修改此code,使得它在一次连接到所有的IP地址。 (这可能吗?)


解决方案

  

我如何修改此code,使其通过我的整个IP地址列表

遍历

您code 迭代整个列表。但它会得到第二个地址,从第一个地址接收所有数据之后。


  

我如何修改此code,使其连接到所有IP地址一次。


如果您封装code为一个地址到一个单独的异步方法,然后你可以先调用它的每个地址,然后等待所有返回工作秒。或者你可以使用LINQ:

 专用异步无效的button1_Click(对象发件人,EventArgs的发送)
{
    VAR listOfIps =新的List<串GT; {192.168.168.193,192.168.168.221};
    等待Task.WhenAll(listOfIps.Select(IP = GT; ReadFromAddress(IP)));
}私人异步任务ReadFromAddress(字符串地址)
{
    IPEndPoint remoteEP =新IPEndPoint(IPAddress.Parse(IP),4001);
    客户端的Socket =新的Socket(AddressFamily.InterNetwork,
                               SocketType.Stream,ProtocolType.Tcp);
    sockets.Add(客户端);
    等待client.ConnectTaskAsync(remoteEP);
    等待ReadAsync(客户端);
}

I have the following code that makes a TCP socket connection to multiple end points as such:

    private async void button1_Click(object sender, EventArgs e)
    {
        var listofIps = new List<string> { "192.168.168.193", "192.168.168.221" };
        foreach (var ip in listofIps)
        {
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(ip), 4001);
            Socket client = new Socket(AddressFamily.InterNetwork,
                                       SocketType.Stream, ProtocolType.Tcp);
            sockets.Add(client);
            await client.ConnectTaskAsync(remoteEP);
            await ReadAsync(client);
        }
    }

    async Task ReadAsync(Socket s)
    {            
        var args = new SocketAsyncEventArgs();
        args.SetBuffer(new byte[1024], 0, 1024);

        var awaitable = new SocketAwaitable(args);

        while (true)
        {
            await s.ReceiveAsync(awaitable);
            int bytesRead = args.BytesTransferred;
            if (bytesRead <= 0) break;

            var data = new ArraySegment<byte>(args.Buffer, 0, bytesRead);
            AppendLog("RX: " + data.DumpHex());
        }
    }

    public static string DumpHex(this ArraySegment<byte> data)
    {
        return string.Join(" ", data.Select(b => b.ToString("X2")));
    }

    public static Task ConnectTaskAsync(this Socket socket, EndPoint endpoint)
    {            
        return Task.Factory.FromAsync(socket.BeginConnect, socket.EndConnect, endpoint, null);
    }

However, the loop doesn't iterate pass the first IP address, because of the await ReadAsync.

Qn 1) How do I modify this code such that it iterates through my whole list of IPs without "awaiting" for the data be received completely. Do I remove the await keyword from await ReadAsync(client)?
Qn 2) How do I modify this code such that it connects to all the IPs at once. (is this possible?)

解决方案

How do I modify this code such that it iterates through my whole list of IPs

Your code will iterate the whole list. But it will get to the second address only after it receives all data from the first address.

How do I modify this code such that it connects to all the IPs at once.

If you encapsulate the code for a single address into a separate async method, you can then first call it for each address and then await all the returned Tasks. Or you could use LINQ:

private async void button1_Click(object sender, EventArgs e)
{
    var listOfIps = new List<string> { "192.168.168.193", "192.168.168.221" };
    await Task.WhenAll(listOfIps.Select(ip => ReadFromAddress(ip)));
}

private async Task ReadFromAddress(string address)
{
    IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(ip), 4001);
    Socket client = new Socket(AddressFamily.InterNetwork,
                               SocketType.Stream, ProtocolType.Tcp);
    sockets.Add(client);
    await client.ConnectTaskAsync(remoteEP);
    await ReadAsync(client);
}

这篇关于使用异步套接字多个套接字连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆