UDP索引超出范围

时间:2013-07-22 17:46:42

标签: sockets udp

我试图弄清楚为什么下面数组的客户端组件超出范围。我知道当你试图访问的数组的元素不存在时会发生这种情况,但我是Socket Programming的新手并试图编写我的第一个UDP脚本但不知道如何处理它。

客户端代码导致args [0]错误:

class EmployeeUDPClient{
    public static void Main(string[] args){
        UdpClient udpc = new UdpClient(args[0],2055);   //Line causing error
        IPEndPoint ep = null;
        while(true){
            Console.Write("Name: ");
            string name = Console.ReadLine();
            if(name == "") break;
            byte[] sdata = Encoding.ASCII.GetBytes(name);
            udpc.Send(sdata,sdata.Length);
            byte[] rdata = udpc.Receive(ref ep);
            string job = Encoding.ASCII.GetString(rdata);
            Console.WriteLine(job);
        }
    }
}

这是运行正常的服务器端代码:

class EmployeeUDPServer{
    public static void Main(){
        UdpClient udpc = new UdpClient(2055);
        Console.WriteLine("Server started, servicing on port 2055");
        IPEndPoint ep = null;
        while(true){
            byte[] rdata = udpc.Receive(ref ep);
            string name = Encoding.ASCII.GetString(rdata);
            string job = ConfigurationSettings.AppSettings[name];
            if(job == null) job = "No such employee";
            byte[] sdata = Encoding.ASCII.GetBytes(job);
            udpc.Send(sdata,sdata.Length,ep);
        }
    }
}

有关我为什么会收到此错误的任何想法?我在同一台计算机上运行2个脚本,这可能是原因吗?

1 个答案:

答案 0 :(得分:0)

错误是因为您没有将任何参数传递给客户端类中的Main()函数。

更改行:

UdpClient udpc = new UdpClient(2055);

致:

string[] host = new string[1];
host[0] = "127.0.0.1";
UdpClient udpc = new UdpClient(host);