c#套接字(连接未建立)

本文关键字:建立 连接 套接字 | 更新日期: 2023-09-27 18:12:28

这是我的客户

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 "Connection is not established on 127.0.0.1:1234"。错误码为10061。请帮忙解决这个问题。

c#套接字(连接未建立)

这绝对是防火墙的问题。

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

ctrl+f并搜索100061。在处理套接字异常时,这是一个非常好的习惯,因为您可以从错误代码编号中获得一些含义(通常,有时这不是很有帮助)。此错误代码属于"无法建立连接,因为目标计算机主动拒绝连接"组。更多细节请点击链接。

也有可能Socket没有被迅速释放,或者你的幸运已经被其他东西使用了。我会先检查防火墙设置,因为这是一件很容易做到的事情。

正如M. Avery所指出的,这听起来绝对像是防火墙/端口问题。我已经测试了你的代码,它运行良好。

如果你在Windows 7上使用Windows防火墙,请查看此链接:http://windows.microsoft.com/en-us/windows/open-port-windows-firewall#1TC=windows-7

您需要指定一个防火墙例外。您可以使用命令行按照这篇方便的知识库文章中所指定的方式来执行此操作。

的例子:

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"