2016-06-20 30 views
1

正在開發客戶端服務器程序。在客戶端,我開發了一個發送數據和接收數據的程序。客戶端/服務器編程,無法將System.net.IPAddress轉換爲字符串

我設法解析一個靜態IP地址,但我嘗試使用IPAddress.Any,但它返回該錯誤。 (無法將System.net.IPAddress轉換爲字符串)。

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

namespace client 
{ 
    class HMSClient 
    { 
     static void Main(string[] args) 
     { 
      try 
      { 
       //---Connect to a port 
       Console.Write("Input port" + System.Environment.NewLine); 
       int PORT_NO = int.Parse(Console.ReadLine()); 
       Console.Write("Input a Command" + System.Environment.NewLine); 
       while (true) 
       { 
        //---data to send to the server--- 
        string commands = Console.ReadLine(); 

        //---create a TCPClient object at the IP and port no.--- 
        //IPAddress SERVER_IP = Dns.GetHostEntry("localhost").AddressList[0]; 

        TcpClient client = new TcpClient(IPAddress.Any, PORT_NO); 

        NetworkStream nwStream = client.GetStream(); 
        byte[] bytesToSend = Encoding.ASCII.GetBytes(commands); 

        //---send the command--- 
        Console.WriteLine("Command: " + commands); 
        nwStream.Write(bytesToSend, 0, bytesToSend.Length); 

        //---read back the response 
        byte[] bytesToRead = new byte[client.ReceiveBufferSize]; 
        int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize); 
        Console.WriteLine("Response: " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead)); 
       } 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine("Client cannot find target to send the command" + Environment.NewLine + e); 
       Console.ReadLine(); 
      } 
     } 
    } 
} 
+0

爲什麼你重新創建客戶端,再而重新連接每個迭代? –

+0

我的意思是我可以將它們移出循環,但是應該是剛剛完成的。 – Freon

+0

它可能會減少資源需求。 –

回答

1

需要的TcpClient Constructor (String, Int32)您所使用的定義如下:

public TcpClient(
    string hostname, 
    int port 
) 

因此,第一個參數需要String,而C#不能將IPAddress隱式轉換爲String。所以你需要在你的IPAddress上使用ToString()

TcpClient client = new TcpClient(IPAddress.Any.ToString(), PORT_NO); 

提示:記住IPAddress.Any representates字符串0.0.0.0,這不是一個有效的IPAddress與一個TcpClient

+1

啊哈!我之前添加了tostring,而沒有給出錯誤的()。這是我感到困惑的原因,謝謝! – Freon

+0

我得到這個錯誤IPv4地址0.0.0.0和IPv6地址:: 0是未指定的地址,不能用作目標地址。你有什麼想法發生了什麼?我覺得它是某種衝突。 – Freon

+0

是的TcpClient需要一個有效的IP地址連接到一個'0.0.0.0'不是一個IP地址。您需要在那裏輸入有效的目標IP地址。 –

0

。任何後,您coud使用的ToString,它會轉換爲字符串,如您在TcpClient的構造

1

TcpClient的構造連接到需要一個字符串作爲第一個參數不是指定一個IP地址目的。

TcpClient client = new TcpClient(IpAddress.Any.ToString(), PORT_NO); 

或IpAddress.Any實際上是「0.0.0.0」

TcpClient client = new TcpClient("0.0.0.0", PORT_NO); 
相關問題