我正在尝试使用StreamSocket和StreamSocketListener来创建代理。目标是让代理做一些事情,但现在我甚至无法做到这一点。当我尝试将响应从原始目标写入连接到代理的客户端时,连接会一直关闭。陌生的事情是它有时会起作用,而不是其他的,可能意味着某种线程或问题?目前,此代理一次只能处理一个请求。
StreamSocketListener server = new StreamSocketListener();
server.ConnectionReceived += this.server_ConnectionReceivedAsync;
await server.BindServiceNameAsync("9000");
以下是处理连接的代码
await originalDestination.ConnectAsync(new EndpointPair(null, string.Empty, this.hostName, this.port));
// Read client data, and forward on to the original destination
await ForwardStream(client.InputStream, originalDestination.OutputStream);
// Get the response from the original destination, and forward it to the client
await ForwardStream(originalDestination.InputStream, client.OutputStream);
这里是ForwardStream函数
bool readMore;
do
{
Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(1024);
await reader.ReadAsync(buffer, 1024, InputStreamOptions.Partial);
readMore = buffer.Length == 1024 ? true : false;
if (buffer.Length != 0)
{
// This is where I get the socket closed exception
await writer.WriteAsync(buffer);
}
else
{
return;
}
}
while (readMore);