簡體   English   中英

獲取請求的地址在其上下文中無效。 在我的聊天應用程序中

[英]Getting The requested address is not valid in its context. in my chat application

所以我在 C# 中編寫了一個聊天應用程序,這是一個控制台應用程序,用戶在其中鍵入收件人的 IPV4 地址。 問題是,當綁定 IP 地址時,消息將來自而不是來自本地主機時返回此地址。

Message=請求的地址在其上下文中無效。 來源=System.Net.Sockets

using System;
 using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
 using System.Net.Sockets;

namespace SimpleTcpSrvr
{
class Program
{
    static void Main(string[] args)
    {
        Console.OutputEncoding = Encoding.UTF8;

        int recv;

        byte[] data = new byte[1024];
        Console.WriteLine("You will need to recieve the password.txt file from your chat buddy.");
        Console.WriteLine("");
        Console.WriteLine("Please enter the IPv4 address of the buddy you are sending messages to.");
        string rip = Convert.ToString(Console.ReadLine());

        IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(rip), 8080);

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

        newsock.Bind(ipep);

// 這是發生錯誤的地方。

        newsock.Listen(10);

        Console.WriteLine("Waiting for a client...");

        Socket client = newsock.Accept();

        IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;

        Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);

        string welcome = "Welcome to encrypted chat. Use ByteOribtPrivacyCannon to  decrypt incoming messages.";

        data = Encoding.UTF8.GetBytes(welcome);

        client.Send(data, data.Length, SocketFlags.None);

        string input;

        while (true)
        {

            data = new byte[1024];

            recv = client.Receive(data);

            if (recv == 0)

                break;

            Console.WriteLine("Client: " + Encoding.UTF8.GetString(data, 0, recv));

            input = Console.ReadLine();

            Console.WriteLine("You: " + input);

            client.Send(Encoding.UTF8.GetBytes(input));
        }

        Console.WriteLine("Disconnected from {0}", clientep.Address);

        client.Close();

        newsock.Close();

        Console.ReadLine();

    }
}

}

為什么會發生這種情況? 非常感謝。

事實上,您的代碼充當“服務器”。 您需要收聽計算機上可用的地址,但您正在綁定另一台主機的 IP 地址。

服務器只能接受連接,不能選擇客戶端。 但是客戶端可以選擇服務器。 您可以嘗試以下代碼來解決它。

服務器:

IPEndPoint ipep = new IPEndPoint(IPAddress.Any,8080);

客戶:

IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("172.xx.xx.xxx"),8080);
//172.xx.xx.xxx is the IPV4 address of your server computer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM