2016-06-20 29 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); 
相关问题