簡體   English   中英

C#套接字(未建立連接)

[英]C# Sockets(Connection is not established)

這是我的客戶

static Socket sck;
    static void Main(string[] args)
    {
        sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint localEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
        try
        {
            sck.Connect(localEndpoint);
        }
        catch (Exception ex)
        {
            Console.Write("Unable to connect local endpoint! \r\n ");
            Main(args);
        }
        string text = Console.ReadLine();
        byte[] data = Encoding.ASCII.GetBytes(text);
        sck.Send(data);
        Console.Write("Data sent ! \r\n");
        Console.Write("Press any key to continue...");
        Console.Read();
        sck.Close();
    }

這是我的服務器。

 static byte[] Buffer { get; set; }
    static Socket sck;
    static void Main(string[] args)
    {
        sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream,  ProtocolType.Tcp);
        sck.Bind(new IPEndPoint(IPAddress.Any, 1234));
        sck.Listen(100);
        Socket accepted = sck.Accept();
        Buffer = new byte[accepted.ReceiveBufferSize];
        int byteReades = accepted.Receive(Buffer);
        byte[] formatted = new byte[byteReades];
        for (int i = 0; i < byteReades; i++)
        {
            formatted[i] = Buffer[i];
        }
        string strData = Encoding.ASCII.GetString(formatted);
        Console.Write(strData + "\r\n");
        sck.Close();
        accepted.Close();
        Console.ReadKey();
    }

當我嘗試運行客戶端以將數據發送到服務器時,我面臨SocketException“未在127.0.0.1:1234上建立連接”。 錯誤代碼為10061。請幫助解決此問題。

這絕對是防火牆問題。

http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx

ctrl + f並搜索100061。這是使用Socket Exceptions時非常好的習慣,因為您可以從錯誤代碼編號中獲得一些含義(通常,有時這不是很有用)。 此錯誤代碼屬於“由於目標計算機主動拒絕連接而無法建立連接”組。 有關鏈接的更多詳細信息。

也有可能套接字沒有被快速釋放,或者您的幸運已經被其他人使用了。 我將首先檢查防火牆設置,因為這是一件很容易的事情。

您需要指定防火牆例外。 您可以按照方便的知識庫文章中的說明使用命令行來執行此操作。

例:

netsh advfirewall firewall add rule name="Socket Test" dir=in action=allow remoteip=127.0.0.1 protocol=TCP localport=1234

然后稍后將其刪除:

netsh advfirewall firewall delete rule name="Socket Test"

正如M. Avery指出的那樣,這無疑聽起來像是防火牆/端口問題。 我已經測試了您的代碼,並且效果很好。

如果您在Windows 7上使用Windows防火牆,請查看以下鏈接: http : //windows.microsoft.com/zh-cn/windows/open-port-windows-firewall#1TC=windows-7

暫無
暫無

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

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