如何解决C#程序将TCP端口13000转发到RDP端口3389?
我正在尝试编写一个测试程序,该程序将在端口13000上侦听tcp并将其转发到端口3389。它开始工作,因为它前后来回传递数据大约6或7次,但是初始套接字丢失
程序因第47行的套接字异常而崩溃: var bytesRead = _forwardSocket.EndReceive(ar);
例外是“现有连接被远程主机强行关闭”
下面是正在运行的程序的屏幕截图。我想念什么?
using System;
using System.Net;
using System.Net.Sockets;
namespace PortForwardTest
{
public class AsynchronousSocketListener
{
private static Socket _forwardSocket;
private static Socket _rdpSocket;
private static readonly byte[] _forwardBuffer = new byte[8192];
private static readonly byte[] _rdpBuffer = new byte[8192];
public static void Main()
{
var ipHostInfo = Dns.GetHostEntry("localhost");
var ipAddress = ipHostInfo.AddressList[0];
var localEndPoint = new IPEndPoint(ipAddress,13000);
// Create a TCP/IP socket.
var listener = new Socket(ipAddress.AddressFamily,SocketType.Stream,ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(100);
listener.BeginAccept(AcceptCallback,listener);
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
// Get the socket that handles the client request.
var listener = (Socket)ar.AsyncState;
_forwardSocket = listener.EndAccept(ar);
_forwardSocket.BeginReceive(_forwardBuffer,_forwardBuffer.Length,SocketFlags.None,ReadCallback,null);
}
public static void ReadCallback(IAsyncResult ar)
{
Console.WriteLine("ReadCallback");
// Read data from the client socket.
var bytesRead = _forwardSocket.EndReceive(ar);
Console.WriteLine($"ReadCallback bytes read: {bytesRead}");
if (bytesRead > 0)
{
SendToRdpServer(bytesRead);
}
_forwardSocket.BeginReceive(_forwardBuffer,null);
}
private static void SendToRdpServer(int bytesRead)
{
if (_rdpSocket == null)
{
Console.WriteLine("**** Establishing the connection to the RDP server");
var ipHostInfo = Dns.GetHostEntry("192.168.3.2");
var ipAddress = ipHostInfo.AddressList[0];
var endPoint = new IPEndPoint(ipAddress,3389);
// Create a TCP/IP socket.
_rdpSocket = new Socket(ipAddress.AddressFamily,ProtocolType.Tcp);
_rdpSocket.Connect(endPoint);
}
Console.WriteLine("Sending the data to the RDP server");
_rdpSocket.Send(_forwardBuffer,bytesRead,SocketFlags.None);
_rdpSocket.BeginReceive(_rdpBuffer,_rdpBuffer.Length,ReadCallbackFromRdpServer,null);
}
public static void ReadCallbackFromRdpServer(IAsyncResult ar)
{
Console.WriteLine("ReadCallbackFromRdpServer");
// Read data from the client socket.
var bytesRead = _rdpSocket.EndReceive(ar);
Console.WriteLine($"ReadCallbackFromRdpServer bytes read: {bytesRead}");
if (bytesRead > 0)
{
Console.WriteLine("Relaying the data back");
_forwardSocket.Send((_rdpBuffer),SocketFlags.None);
}
_rdpSocket.BeginReceive(_rdpBuffer,null);
}
}
}
这是输出的更新图像,显示RDP连接仅执行一次。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。