gpt4 book ai didi

c# - 搭建C#异步TCP代理服务器

转载 作者:可可西里 更新时间:2023-11-01 02:56:28 24 4
gpt4 key购买 nike

我正在尝试为我的企业构建一个简单的 C# TCP 代理,这样我就可以阻止我的员工访问某些网站。一切都很好,除了我无法查看用户尝试访问的网站...我可以看到用户已连接到我的代理服务器,所以我知道我正在建立连接,但 OnRecieve 回调甚至没有触发。我从套接字读取错误吗?

这是我的代码:

internal class AsyncState
{
public const int BufferSize = 4096;
public byte[] Buffer = new byte[AsyncState.BufferSize];
public Socket Socket;
public StringBuilder Content = new StringBuilder();
}

private void OnLoad(object sender, EventArgs e)
{
IPAddress[] addressCollection = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ipAddress in addressCollection)
{
if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
{
localEndPoint = new IPEndPoint(ipAddress, 8080);
Console.WriteLine("Local IP address found... " + localEndPoint.ToString());
break;
}
}

isListening = true;

thread = new Thread(new ThreadStart(
delegate()
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(localEndPoint);
serverSocket.Listen(10);

while (isListening)
{
resetEvent.Reset();

Console.WriteLine("Waiting for clients...");
serverSocket.BeginAccept(new AsyncCallback(OnAccept), serverSocket);

resetEvent.WaitOne();
}
}));

thread.Start();
}
}

private void OnAccept(IAsyncResult result)
{
resetEvent.Set();

Socket clientSocket = (result.AsyncState as Socket).EndAccept(result);
Console.WriteLine("Client has connected... " + clientSocket.RemoteEndPoint.ToString());

AsyncState state = new AsyncState();
state.Socket = clientSocket;
state.Socket.BeginReceive(state.Buffer, 0, AsyncState.BufferSize, SocketFlags.None, new AsyncCallback(OnRecieve), state);
}

private void OnRecieve(IAsyncResult result)
{
AsyncState state = result.AsyncState as AsyncState;

int totalRead = state.Socket.EndReceive(result);
if (totalRead > 0)
{
state.Content.Append(Encoding.ASCII.GetString(state.Buffer, 0, totalRead));
state.Socket.BeginReceive(state.Buffer, 0, AsyncState.BufferSize, SocketFlags.None, new AsyncCallback(OnRecieve), state);
}
else
{
if (state.Content.Length > 1)
Console.WriteLine("Message recieved from client... " + state.Content.ToString());

state.Socket.Close();
}
}

最佳答案

构建一个运行良好的代理绝非易事,因为您必须在两个方向上理解和处理 HTTP 等...

我建议为此使用现有的库或一些可配置的代理...

备注:

我不知道你在哪个司法管辖区,但在员工不知情/不同意的情况下使用此类技术在某些地方可能会成为问题......

另一点:我不会使用这种方法,而是告诉员工停止滥用公司的互联网连接 1-3 次,如果这不起作用,我宁愿解雇那个人......这样的员工不仅是滥用公司的互联网连接,但在最坏的情况下会使公司处于危险之中(病毒/木马等)并且还会欺骗公司(如果他在工作时间这样做)...

关于c# - 搭建C#异步TCP代理服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8039812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com