C#简单的UDP通信

时间:2015-10-08 12:07:49

标签: c# network-programming udp

我正在学习如何使用UDP与同一台机器上的其他应用程序进行通信,所以我将通过以下程序来获取概念,但是当我运行它时,我收到一条错误消息,话说:

System.dll中发生未处理的“System.Net.Sockets.SocketException”类型异常

我错过了什么或做错了什么?有人还可以简要地向我解释如果程序运行会发生什么?谢谢

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;


namespace udpClient
{
    public class Program
    {
        public static void Main(string[] args)
        {
            byte[] data = new byte[1024];
            string input, stringData;

            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            string welcome = "Hello, are you there?";
            data = Encoding.ASCII.GetBytes(welcome);
            server.SendTo(data, data.Length, SocketFlags.None, ipep);

            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)sender;

            data = new byte[1024];
            int recv = server.ReceiveFrom(data, ref Remote);

            Console.WriteLine("Message received from {0}:", Remote.ToString());
            Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

            // In Unity3D, replace this with update or coroutine.
            while (true)
            {
                input = Console.ReadLine();

                if (input == "exit")
                    break;

                server.SendTo(Encoding.ASCII.GetBytes(input), Remote);
                data = new byte[1024];
                recv = server.ReceiveFrom(data, ref Remote);
                stringData = Encoding.ASCII.GetString(data, 0, recv);
                Console.WriteLine(stringData);
            }

            Console.WriteLine("Stopping client ..");
            server.Close();

            // Console.WriteLine("\nPress any key ...");
            // Console.ReadKey();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

请查看代码的快速修复,请注意此结构仅供演示使用,不适用于生产。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace testUDP
{
class Program
{

    static volatile Boolean receivingThreadStarted = false;

    public static void DoReceiveFrom()
    {
        byte[] data = new byte[1024];
        IPEndPoint sender = new IPEndPoint(IPAddress.Any, 9050);
        EndPoint Remote = (EndPoint)sender;
        Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        server.Bind(sender);
        receivingThreadStarted = true;
        int recv = server.ReceiveFrom(data, ref Remote);
        Console.WriteLine("Message received from {0}:", Remote.ToString());
        Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
    }


    static void Main(string[] args)
    {
         byte[] data = new byte[1024];
        string input;

        IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
        Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        ThreadStart threadDelegate = new ThreadStart(DoReceiveFrom);
        Thread newThread = new Thread(threadDelegate);
        newThread.Start();

        // Waiting to start the receiving thread.
        while (!receivingThreadStarted) Thread.Sleep(100);

        string welcome = "Hello, are you there?";
        data = Encoding.ASCII.GetBytes(welcome);
        server.SendTo(data, data.Length, SocketFlags.None, ipep);

        while (true)
        {
            input = Console.ReadLine();

            if (input == "exit")
                break;               
        }

        Console.WriteLine("Stopping client ..");
        server.Close();

    }
}

}