我正在尝试使用 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);