套接字客户端/服务器应用程序没有';尽管开放了端口,但无法通过互联网工作
本文关键字:放了 工作 互联网 应用程序 服务器 客户端 套接字 | 更新日期: 2023-09-27 18:25:34
我已经用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;
}
}
}
您遇到问题,因为您正试图使用NAT(hairping)通过外部地址连接到本地网络上的服务器。通常情况下,如果可用,您应该使用内部地址连接到服务器应用程序,外部连接仍然可以通过NAT使用外部地址。如果这只是一个测试问题,并且您的路由器不支持NAT发夹、NAT环回或NAT反射,你可以四处寻找绕过发夹的方法(通常是通过设置自己的DNS),也可以让别人帮助你从外部连接进行测试。