我用c#.NET套接字编写了一个TCP / IP服务器。使用本地网络它工作正常,但当我尝试通过互联网使用它时,客户端无法连接到服务器。
我确定我已经在路由器和Windows防火墙(客户端和服务器)中打开了我的端口(14999),并且我还将我的计算机端口14999映射到路由器上的端口。
即便如此,我也得到了“现有的公司 连接被远程主机强行关闭。“当我的客户端应用程序尝试通过互联网连接到我的服务器时。
我注意到了一件事。
当我使用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;
}
}
}
答案 0 :(得分:1)
您遇到问题,因为您尝试使用NAT(发夹)通过外部地址连接到本地网络上的服务器。通常,您应该使用内部地址连接到服务器应用程序(如果可用),外部连接仍然可以通过NAT使用外部地址。如果这只是测试的问题,并且您的路由器不支持NAT发夹,NAT环回或NAT反射,您可以环顾四周寻找发夹的方法(通常通过设置您自己的DNS)或让某人帮助您从外部连接测试。