【问题标题】:Sockets Client/Server application doesn't work over internet despite opened port [closed]尽管打开了端口,但套接字客户端/服务器应用程序无法在 Internet 上运行 [关闭]
【发布时间】:2015-12-03 21:56:20
【问题描述】:

我用 c# .NET 套接字编写了一个 TCP/IP 服务器。使用本地网络它工作正常,但是当我尝试通过互联网使用它时,客户端无法连接到服务器。

我确定我已经在路由器和 Windows 防火墙(客户端和服务器)中打开了我的端口 (14999),并且我还将我的计算机端口 14999 映射到了路由器上的端口。

即使这样,我也会得到“现有的合作 连接被远程主机强行关闭。”当我的客户端应用程序尝试通过 Internet 连接到我的服务器时。

我注意到一件事。

当我使用 Visual Studio 调试服务器并使用 http://www.yougetsignal.com/tools/open-ports/ 检查 14999 端口时,代码会遇到断点。

我一直被我们的这个困扰,有没有人知道我能做什么?

非常感谢大家!

这是我的客户端应用程序代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Web.Script.Serialization;
using System.Security.Cryptography;
using System.IO;

namespace ConsoleApplication1
{
    public class Person
    {
        public string name;
        public int age;
    }
    // State object for receiving data from remote device.
    public class StateObject
    {
    // Client socket.
    public Socket workSocket = null;
    // Size of receive buffer.
    public const int BufferSize = 256;
    // Receive buffer.
    public byte[] buffer = new byte[BufferSize];
    // Received data string.
    public StringBuilder sb = new StringBuilder();
}

public class AsynchronousClient
{
    // The port number for the remote device.
    private const int port = 14999;

    // ManualResetEvent instances signal completion.
    private static ManualResetEvent connectDone =
        new ManualResetEvent(false);
    private static ManualResetEvent sendDone =
        new ManualResetEvent(false);
    private static ManualResetEvent receiveDone =
        new ManualResetEvent(false);

    // The response from the remote device.
    private static String response = String.Empty;

    private static void StartClient()
    {
        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            // The name of the 
            // remote device is "host.contoso.com".
            IPHostEntry ipHostInfo = Dns.GetHostEntry("MY PUBLIC IP");
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
            Socket client = new Socket(AddressFamily.Unspecified,
                    SocketType.Stream, ProtocolType.Tcp);
            for (;;)
            {
                // Create a TCP/IP socket.


                // Connect to the remote endpoint.
                client.BeginConnect(remoteEP,
                    new AsyncCallback(ConnectCallback), client);
                connectDone.WaitOne();

                User user = new User() { name = "asdfasdfasdf", adress = "asdfasdfas", country = "asdfasdf", email = "example@example.com", locality = "asdfasdf", pass = "asdfasdf", state = "aasdfasd", surname = "asdfasdfasdf", telfNum = 123123 };

                loginPublic login = new loginPublic() { email = "example@example.com", pass = "asdfasdfasdfas" };

                accion accion = new accion() { act = 2, data = login };

                var die = new JavaScriptSerializer().Serialize(accion);

                //string guy = SPHFS.EncryptStringAES(die, "HFSIsAwesome12@.");
                string guy = die;
                // Send test data to the remote device.
                Send(client, guy);
                sendDone.WaitOne();

                // Receive the response from the remote device.
                Receive(client);
                receiveDone.WaitOne();

                respuesta Resp = new JavaScriptSerializer().Deserialize<respuesta>(response);
                Console.WriteLine("Message : {0} and Result : {1}", Resp.Message, Resp.Result);
                Thread.Sleep(100);
                // Write the response to the console.

            }

            // Release the socket.

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            Console.ReadLine();
        }
    }

    private static void ConnectCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;

            // Complete the connection.
            client.EndConnect(ar);

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

            // Signal that the connection has been made.
            connectDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            Console.ReadLine();
        }
    }

    private static void Receive(Socket client)
    {
        try
        {
            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = client;

            // Begin receiving the data from the remote device.
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                ReceiveCallback, state);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            Console.ReadLine();
        }
    }

    private static void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the state object and the client socket 
            // from the asynchronous state object.
            StateObject state = (StateObject)ar.AsyncState;
            Socket client = state.workSocket;

            // Read data from the remote device.
            int bytesRead = client.EndReceive(ar);

            if (bytesRead > 0)
            {
                // There might be more data, so store the data received so far.
                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                // Get the rest of the data.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    ReceiveCallback, state);
            }
            else
            {
                // All the data has arrived; put it in response.
                if (state.sb.Length > 1)
                {
                    response = state.sb.ToString();
                }
                // Signal that all bytes have been received.
                receiveDone.Set();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
            Console.ReadLine();
        }
    }

    private static void Send(Socket client, String data)
    {
        for(;;)
        {
            try
            {
                // Convert the string data to byte data using ASCII encoding.
                byte[] byteData = Encoding.ASCII.GetBytes(data);

                // Begin sending the data to the remote device.
                client.BeginSend(byteData, 0, byteData.Length, 0,
                    SendCallback, client);
                break;
            }
            catch
            {

            }
        }


    }

    private static void SendCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;

            // Complete sending the data to the remote device.
            int bytesSent = client.EndSend(ar);
            Console.WriteLine("Sent {0} bytes to server.", bytesSent);

            // Signal that all bytes have been sent.
            sendDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    public static int Main(String[] args)
    {
        StartClient();
        return 0;
    }
    public class User
    {
        public string name { get; set; }
        public string surname { get; set; }
        public string adress { get; set; }
        public string locality { get; set; }
        public string country { get; set; }
        public string state { get; set; }
        public string email { get; set; }
        public int telfNum { get; set; }
        public string pass { get; set; }
        public LicenceDAO licencia { get; set; }
    }

    public class LicenceDAO
    {
        public decimal payment;
        public DateTime nextPayment;
        public bool state;
        public string administrator;
    }

    public class accion
    {
        public int act;
        public string key;
        public object data;
    }

    public class respuesta
    {
        public bool Result;
        public string Message;
    }

    public class loginPublic
    {
        public string email;
        public string pass;
    }



  }
}

【问题讨论】:

  • 当您说the code hits a breakpoint 时,您的意思是您可以看到执行转移到接受连接的代码中?因此,如果在您指定的端口上尝试进行外部连接,您的服务器代码会得到那么多,但是当您尝试使用它而不是第三方工具进行连接时,您的客户端应用程序不会产生相同的效果?
  • 是的,就是这样。感谢您的回答!
  • 您可以从您尝试与客户端连接的计算机上 ping 公共地址和端口吗? ping &lt;public_ip&gt;:&lt;port&gt;.
  • 不,我无法 ping 我的公共地址:S 我认为这是主要问题,我该如何解决?
  • 这不是你的代码问题,是你的路由问题。您正在尝试做的事情称为发夹 NAT 或发夹。

标签: c# .net sockets tcp


【解决方案1】:

您遇到问题是因为您尝试使用 NAT(发夹)通过外部地址连接到本地网络上的服务器。通常,如果可用,您应该使用内部地址连接到您的服务器应用程序,外部连接仍然可以通过 NAT 使用外部地址工作。如果这只是一个测试问题,并且您的路由器不支持 NAT 发夹、NAT 环回或 NAT 反射,您可以四处寻找绕过发夹的方法(通常通过设置您自己的 DNS)或找人帮助您从外部连接进行测试。

【讨论】:

  • 谢谢!!我已将另一台计算机连接到我的移动网络,它现在可以正常工作了^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-13
  • 2014-07-23
  • 2020-09-13
相关资源
最近更新 更多