2013-03-03 67 views
1

我不知道如何解決這個問題,但我遇到了這個問題,特別是 拋出新的System.ArgumentException(「語法:timeclnt ServerName PortNumber 1」); .....有什麼線索可以做什麼?服務器應用程序將需要提供一個端口號來偵聽,但是如何?UDP服務器應用程序

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

public class TimeClient 
{ 
    public static int Main(String[] args) 
    { 
     if (args.Length < 2 || args.Length > 2) 
      throw new System.ArgumentException("Syntax: timeclnt ServerName PortNumber 1"); 

     String hostName = args[0]; 
     int portNum = Int32.Parse(args[1]); 

     try 
     { 
      // Define a string to send to the server 
      string stringData = "From the timeClient"; 

      // Encode it properly 
      byte[] data = Encoding.ASCII.GetBytes(stringData); 

      // Define a UDP client connection 
      UdpClient client = new UdpClient(); 

      // Send some data to the server 
      client.Send(data, data.Length, hostName, portNum); 

      //where to listen for a UDP response 
      IPEndPoint recvpt = new IPEndPoint(IPAddress.Any, 0); 

      // get the data back from the server 
      byte[] receivedData = client.Receive(ref recvpt); 

      // output the data received 
      Console.WriteLine("{0}", Encoding.ASCII.GetString(receivedData)); 

      // all done 
      client.Close(); 
     } 

     catch (Exception e) 
     { 
      // display an error 
      Console.WriteLine(e.ToString()); 
     } 

     return 0; 
    } 
} 
+0

1 。)爲什麼不args.Length!= 2? 2.)例外說3個參數:ServerName PortName 1 < - 表示它總是!= 2 3)如果用戶切換參數Servername和Port,則會得到另一個異常,因爲字符串servername不能轉換爲整數。 – 2013-03-03 05:05:07

+0

@Alina B.我不知道如何解決它?我試圖把它放進去,但它表示標識符預計。我不是很喜歡c# – Cliff 2013-03-03 13:52:51

+0

懸崖,你爲什麼用這種方式編輯你的問題? – 2013-04-16 18:32:49

回答

0

根據您的if條件推測,您沒有傳遞完全2個參數。如果你想3個參數,你的條件更改爲

if (args.Length < 3 || args.Length > 3) 
+0

我試圖改變,但它沒有區別。我應該使用什麼端口號? – Cliff 2013-03-03 13:49:43

0

正如我在評論中提及:

System.ArgumentException( 「語法:timeclnt服務器名端口號1」);

這意味着有將傳遞3個參數給你的代碼:服務器,端口號和1

有了3個參數傳遞給你的方法,你必須改變你的if語句:

if (args.Length != 3)