我在c#套接字中编写HTTP代理。代理必须在HTML文件中进行更改。一切正常,直到我替换大于或小于原始单词的文本。例如,如果我将“abcde”替换为“abcde”代理工作完美,但如果我将“abcde”替换为“ab”,我在socket.send中得到套接字异常“已建立的连接被主机中的软件中止”方法。我已禁用防火墙和Windows防御者。
接受浏览器套接字:
static void Main(string[] args)
{
TcpListener tcpl = new TcpListener(IPAddress.Parse("127.0.0.1"), 1024);
tcpl.Start();
while (true)
{
Socket sock = tcpl.AcceptSocket();
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
RequestHandler rh = new RequestHandler(sock);
rh.Handle();
}
}
处理请求:
public void Handle()
{
string header = GetHeader(browserSocket, 1);
string host = AnalyzeHeader(header);
if (string.IsNullOrEmpty(header) || string.IsNullOrEmpty(host))
{
browserSocket.Close();
return;
}
Socket destServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress[] addresslist = Dns.GetHostAddresses(host);
IPEndPoint remoteEP = new IPEndPoint (addresslist[0], 80);
destServerSocket.Connect(remoteEP);
SendRequest(destServerSocket, header);
header = GetHeader(destServerSocket, 0);
SendRequest(browserSocket, header);
int receivedBytes = 1;
const int BUFSZ = 1024;
byte[] buffer = new byte[BUFSZ];
while (receivedBytes > 0)
{
if (destServerSocket.Poll(100000, SelectMode.SelectRead))
{
receivedBytes = destServerSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
if (header.Contains("Content-Type: text/html"))
{
string charset = GetCharset(header);
charset = string.IsNullOrEmpty(charset) ? "UTF-8" : charset;
var inputEncoding = Encoding.GetEncoding(charset);
var text = inputEncoding.GetString(buffer);
if (text.Contains("abcde"))
{
text = text.Replace("abcde", "ab");
buffer = inputEncoding.GetBytes(text);
receivedBytes = buffer.Length;
}
}
this.browserSocket.Send(buffer, receivedBytes, SocketFlags.None); //Exception 10053
}
else
{
receivedBytes = 0;
}
}
this.browserSocket.Shutdown(SocketShutdown.Both);
this.browserSocket.Close();
}
我曾尝试将Content-Length添加到响应标头,但仍会出现错误。您认为问题是什么?经过几天的研究,我已经没事了。