互联网上的 C# 套接字

5 c# sockets

我成功地用 C# 编写了一个在局域网下完美运行的客户端服务器程序,我们使用了 TcpListener 和 TcpSocket 类。

虽然我们无法让它在互联网上工作,但我知道这与防火墙、路由器端口阻塞等有关。

我们转发了我们使用的端口并关闭了防火墙,但仍然没有运气。

为了使这项工作发挥作用,我必须做些什么不同的事情?像使用某个端口一样可以正常工作吗?“Msn Messenger”怎么说呢?

服务器代码:

  private static TcpListener serverTcpListener;

   public static bool Run()
    {
        // Initialize new thread for client communications
        Thread listenThread = new Thread(new ThreadStart(ListenForClients));
        
        // Initialize TCP listener and attempt to start
        ServerTcpListener = new TcpListener(IPAddress.Any, 3000);

        try
        {
            ServerTcpListener.Start();
        }
        catch (SocketException)
        {
            return false;
        }


        // Start client communications thread
        listenThread.Start();

        return true;
    }





    
    public static void ListenForClients()
    {
        while (true)
        {
            TcpClient client = ServerTcpListener.AcceptTcpClient();
            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
            clientThread.Start(client);
        }
    }
Run Code Online (Sandbox Code Playgroud)

客户代码:

    private TcpClient myClient;
    private NetworkStream clientStream;

   public InitializeResult Initialize()
    {
        IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);

        try
        {
            MyClient.Connect(serverEndPoint);
        }
        catch (SocketException)
        {
            return InitializeResult.AccessError;
        }
        catch (ArgumentNullException)
        {
            return InitializeResult.NullRemote;
        }

        try
        {
            ClientStream = MyClient.GetStream();
        }
        catch (Exception)
        {
            return InitializeResult.StreamFail;
        }

        if (!Authenticate())
        {
            return InitializeResult.AuthenticateFail;
        }


        return InitializeResult.Success;
        
    }
Run Code Online (Sandbox Code Playgroud)

seh*_*ehe 0

您需要绑定到外部网卡。您很可能绑定到环回适配器

如果您提供一些代码,我们也许可以诊断(甚至修复)问题