繁体   English   中英

客户端/服务器编程,无法将System.net.IPAddress转换为String

[英]Client/Server Programming, Cannot convert System.net.IPAddress to String

我正在开发客户端服务器程序。 在客户端,我开发了一个发送和接收数据的程序。

我设法解析了一个静态IP地址,但尝试使用IPAddress.Any,但它返回了该错误。 (无法将System.net.IPAddress转换为String)。

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();
            }
        }
    }
}

您使用的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代表字符串0.0.0.0 ,它不是与TcpClient连接的有效IPAddress

TcpClient构造函数将字符串作为第一个参数,而不是IpAddress对象。

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);

您可以在.Any之后使用.ToString,它将根据需要在TcpClient构造函数中转换为字符串

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM