2

我正在尝试在 C# 中创建一个非常简单的客户端/服务器,基本上我目前要做的就是让客户端连接到服务器,这就是我出错的地方。我的服务器启动正常,但是当我尝试启动客户端时出现此错误:

The requested address is not valid in this context
  at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x00000] in <filename unknown>:0
  at Client.Client.Main (System.String[] args) [0x00000] in <filename unknown>:0

我现在拥有的基本客户端如下

        try
        {
            IPAddress ipAddress = IPAddress.Parse("0.0.0.0");
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 8001);

            Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                sender.Connect(remoteEP);                    

                Console.WriteLine("Connected to: " + remoteEP);

                byte[] msg = Encoding.ASCII.GetBytes("Testing");

                sender.Send(msg);


                sender.Shutdown(SocketShutdown.Both);
                sender.Close();

            }

            catch (Exception e)
            {
                Console.WriteLine(e.Message + "\n" + e.StackTrace);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message + "\n" + e.StackTrace);
        }
4

1 回答 1

5

这不是一个有效的 IP 地址。对于本地主机(您自己的机器),这就是您想要的

   IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
于 2013-03-09T04:51:15.467 回答