You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

公网IP连接触发Socket异常,localhost连接正常问题求助

Socket公网IP连接失败,localhost正常的问题

错误提示

System.Net.Sockets.SocketException (0x80004005): 连接尝试失败,因为连接方在一段时间后未正确响应,或者已建立的连接失败,因为连接的主机未能响应

问题现象

  • 仅尝试通过公网IP连接时触发该错误,使用localhost连接完全正常
  • 已确认公网IPv4地址对应的端口已完成端口转发,且电脑防火墙已允许该端口的入站和出站请求
  • 预期能收到服务端返回的测试消息"This is a test",实际触发上述Socket异常

客户端代码(C#)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace RemoteBG
{
    public partial class Form1 : Form
    {
        Socket client;
        IPEndPoint remote;

        public Form1()
        {
            InitializeComponent();

            IPHostEntry host = Dns.GetHostEntry("PUBLICIP");
            IPAddress ipAddress = host.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, PORT);
            Socket sender = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            client = sender;
            remote = remoteEP;
        }

        private void TextUpdate(String s)
        {
            textBox1.AppendText(s + System.Environment.NewLine);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            byte[] bytes = new byte[1024];
            try
            {
                // Connect to Remote EndPoint
                client.Connect(remote);

                Console.WriteLine("Socket connected to {0}",
                    client.RemoteEndPoint.ToString());

                // Encode the data string into a byte array.
                byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");

                // Send the data through the socket.
                int bytesSent = client.Send(msg);

                // Receive the response from the remote device.
                int bytesRec = client.Receive(bytes);
                Console.WriteLine("Echoed test = {0}",
                    Encoding.ASCII.GetString(bytes, 0, bytesRec));

                // Release the socket.
                client.Shutdown(SocketShutdown.Both);
                client.Close();

            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
            }
            catch (SocketException se)
            {
                TextUpdate("Error connecting to Zang's PC. Error: " + se.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unexpected exception : {0}", ex.ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {

        }
    }
}

服务端代码(C#)

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace RemoteBGServer
{
    class Program
    {
        public static int Main(String[] args)
        {
            StartServer();
            return 0;
        }

        public static void StartServer()
        {
            IPHostEntry host = Dns.GetHostEntry("LOCALIP");
            IPAddress ipAddress = host.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, PORT);

            try
            {
                // Create a Socket that will use Tcp protocol
                Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                // A Socket must be associated with an endpoint using the Bind method
                listener.Bind(localEndPoint);
                // Specify how many requests a Socket can listen before it gives Server busy response.
                // We will listen 10 requests at a time
                listener.Listen(10);

                Console.WriteLine("Waiting for a connection...");
                Socket handler = listener.Accept();

                // Incoming data from the client.
                string data = null;
                byte[] bytes = null;

                while (true)
                {
                    bytes = new byte[1024];
                    int bytesRec = handler.Receive(bytes);
                    data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    if (data.IndexOf("<EOF>") > -1)
                    {
                        break;
                    }
                }

                Console.WriteLine("Text received : {0}", data);

                byte[] msg = Encoding.ASCII.GetBytes(data);
                handler.Send(msg);
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("\n Press any key to continue...");
            Console.ReadKey();
        }
    }
}

注:代码中的PUBLICIP/LOCALIP和PORT已做脱敏处理,实际使用的是公网IPv4地址及已完成端口转发的特定端口


内容的提问来源于stack exchange,提问作者zang227

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 14:15:40