尽管打开了端口,但套接字客户端/服务器应用程序无法通过 Internet 工作 [英] Sockets Client/Server application doesn't work over internet despite opened port

查看:34
本文介绍了尽管打开了端口,但套接字客户端/服务器应用程序无法通过 Internet 工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've programmed a TCP/IP server with c# .NET Sockets. Using local network it works fine, but when i try to use it over the internet the client can't connect to the server.

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

I'm sure i've opened my port (14999) in the router and in windows firewall(both, client and server) and i also mapped my computer port 14999 to the one on the router.

即使这样我得到一个现有的合作nnection 被远程主机强行关闭."当我的客户端应用程序尝试通过 Internet 连接到我的服务器时.

Even with this i get "An existing co nnection was forcibly closed by the remote host." When my client application try to connect over the internet to my server.

我注意到一件事.

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

When i have my server debugging with Visual Studio, and i use http://www.yougetsignal.com/tools/open-ports/ to check the 14999 port, the code hits a breakpoint.

我一直坚持这个我们的,有人知道我能做什么吗?

I've been stucked with this ours, is there anybody who knows what can i do ?

非常感谢大家!

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

Here is my client app code :

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;
    }



  }
}

推荐答案

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

You are having an issue because you are attempting to connect to a server on your local network via the external address using NAT (hairpinning). Normally you should connect to your server application using the internal address if available, external connections would still work using the external address through NAT. If this is just an issue for testing and your router does not support NAT hairpinning, NAT loopback, or NAT reflection, you can either look around for ways to get around the hairpin (usually by setting up your own DNS) or have someone help you test from an external connection.

这篇关于尽管打开了端口,但套接字客户端/服务器应用程序无法通过 Internet 工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆