C#查找客户端然后创建套接字连接

时间:2017-06-07 14:36:59

标签: c# sockets

我一直在尝试使用一些代码来查找运行我的应用的网络上的其他计算机。首先,我播放和收听那些广播。在那之后,我在下一步有点迷失。一旦计算机A知道计算机B的IP地址,因为广播如何将计算机B置于接受套接字连接的状态。那么计算机A如何开始这种连接?

此外,我尝试使用Multicast进行广播,但无法使用它。如果有人有额外的时间,他们也可以表明。

启动侦听器和发件人:

private static void StartServer()
    {
        Task.Factory.StartNew(async () =>
        {
            await StartListeningAsync();
        });

    }

    private static void StartClient()
    {
        Task.Factory.StartNew(async () =>
        {
            await StartSendingAsync();
        });


    }

那些内在的方法:

    private static async Task StartSendingAsync()
    {

        try
        {
            using (UdpClient _broadcaster = new UdpClient())
            {
                var ipHost = Dns.GetHostEntry("");
                var ipAddr = ipHost.AddressList[ipHost.AddressList.Count() - 1];


                IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, PORT);
                var ipAddress = Encoding.ASCII.GetBytes(ipAddr.ToString());
                for (int x = 0; x < 10; x++)
                {
                    _broadcaster.Send(ipAddress, ipAddress.Count(), ip);
                    await Task.Delay(TimeSpan.FromSeconds(6));
                }
            }
        }
        catch (Exception ex)
        {

        }


    }

    private static async Task StartListeningAsync()
    {


        while (true)
        {
            using (UdpClient _listener = new UdpClient(PORT))
            {
                try
                {
                    IPEndPoint ip = new IPEndPoint(IPAddress.Any, PORT);
                    var incoming = await _listener.ReceiveAsync();
                    NewPing(incoming.Buffer, incoming.RemoteEndPoint);
                    await Task.Delay(TimeSpan.FromSeconds(10));
                }
                catch (SocketException ex)
                {
                    if (ex.SocketErrorCode == SocketError.TimedOut)
                    {
                        //Time out that's fine
                    }
                }

            }
        }

    }

当听众听到广播时会发生什么:

private static void NewPing(byte[] incoming, IPEndPoint rem)
    {

        Console.WriteLine($"New ping from {rem.ToString()}, attempting to connect!");

        //What should happen here now that one of the computer's know the other exists?
        //Start some kind of Socket Accepting method?

    }

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你想让一台机器发出UDP广播,然后在两者之间建立TCP连接吗?

我执行以下步骤:

  • B 正在侦听UDP广播
  • A 希望与 B 进行TCP连接,所以
  • A 开始侦听传入的TCP连接
  • A 发出广播说法&#34;我正在倾听&#34;
  • B 接收广播并尝试连接 A

我创建了两个示例控制台应用程序,一个服务器,一个客户端:

服务器

using System;
using System.Net;
using System.Net.Sockets;

class Program
{
    static void Main(string[] args)
    {
        TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, 11220));
        listener.Start();
        listener.AcceptSocketAsync().ContinueWith((t) => HandleClient(t.Result));
        Console.WriteLine($"Listening for TCP connections at port 11220...");

        using (UdpClient broadcaster = new UdpClient(AddressFamily.InterNetwork))
        {
            broadcaster.EnableBroadcast = true;
            Console.WriteLine("Broadcasting...");
            broadcaster.Send(new byte[] { 1, 2, 3 }, 3, new IPEndPoint(IPAddress.Broadcast, 11221));
        }

        while (Console.ReadKey(true).Key != ConsoleKey.Q)
        {
            Console.WriteLine("Press 'Q' to quit");
        }
    }

    static void HandleClient(Socket socket)
    {
        Console.WriteLine($"TCP connection accepted ({socket.RemoteEndPoint})!");
    }
}

<强>客户端:

using System;
using System.Net;
using System.Net.Sockets;

class Program
{
    static void Main(string[] args)
    {
        using (UdpClient client = new UdpClient(11221, AddressFamily.InterNetwork))
        {
            Console.WriteLine("Waiting for broadcast...");
            client.EnableBroadcast = true;
            client.ReceiveAsync().ContinueWith((t) => HandleBroadcast(t.Result)).Wait();
        }

        Console.WriteLine("Press any key to continue");
        Console.ReadKey(true);
    }

    static void HandleBroadcast(UdpReceiveResult result)
    {
        Console.WriteLine($"Received broadcast from {result.RemoteEndPoint}, attempting to connect via TCP");
        Socket socket = new Socket(result.RemoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        socket.Connect(new IPEndPoint(result.RemoteEndPoint.Address, 11220));
    }
}

首先启动客户端,然后启动服务器。广播中发送的数据只是虚拟数据,但您可以包含一些信息,例如服务器正在侦听的TCP端口号。

PS。请记住,这只是一个概念证明。