I am having an issue working with async methods - namely nested async.
I start off a background task:
public sealed class StartupTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
taskInstance.GetDeferral();
ServerWorkers.WebServer server = new ServerWorkers.WebServer();
await ThreadPool.RunAsync(workItem =>
{
AnotherSync.Get();
server.Start();
});
}
public static async void Get()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Shared.URL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Shared.HeaderType));
using (var response = await client.GetAsync(route + "?" + GeneralTags.COMPANY_REF + "=" + ApplicationObject.CompanyRef)) //.Result)
{
if (response.IsSuccessStatusCode)
{
ApplicationObject.PrintData = JsonConvert.DeserializeObject<Model.Print>(response.Content.ReadAsStringAsync().Result);
}
else
{
evError(new Exception(String.Format("{0}: {1}", (int)response.StatusCode, response.ReasonPhrase)), ErrorTags.PRINT_GET);
}
}
}
}
internal class WebServer
{
private const uint BufferSize = 8192;
public void Start()
{
StreamSocketListener listener = new StreamSocketListener();
listener.BindServiceNameAsync("8080");
listener.ConnectionReceived += async (sender, args) =>
{
StringBuilder request = new StringBuilder();
using (IInputStream input = args.Socket.InputStream)
{
byte[] data = new byte[BufferSize];
IBuffer buffer = data.AsBuffer();
uint dataRead = BufferSize;
while (dataRead == BufferSize)
{
await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
dataRead = buffer.Length;
}
}
using (IOutputStream output = args.Socket.OutputStream)
{
using (Stream response = output.AsStreamForWrite())
{
byte[] bodyArray = Encoding.UTF8.GetBytes("<html><body>Hello, World!</body></html>");
var bodyStream = new MemoryStream(bodyArray);
var header = "HTTP/1.1 200 OK\r\n" +
$"Content-Length: {bodyStream.Length}\r\n" +
"Connection: close\r\n\r\n";
byte[] headerArray = Encoding.UTF8.GetBytes(header);
await response.WriteAsync(headerArray, 0, headerArray.Length);
await bodyStream.CopyToAsync(response);
await response.FlushAsync();
}
}
};
}
}
Then my app acts a web server.. It does not exit out.
If I add this so I have:
public async void Run(IBackgroundTaskInstance taskInstance)
{
taskInstance.GetDeferral();
ServerWorkers.WebServer server = new ServerWorkers.WebServer();
await ThreadPool.RunAsync(workItem =>
{
AnotherSync.Get();
AnotherSync.Get();
server.Start();
});
}
internal class AnotherSync
{
public static event delError evError;
private const string route = "/api/Print";
static wsPrint.IPrint wsPrint = new wsPrint.PrintClient();
public static void Get()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Shared.URL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Shared.HeaderType));
using (var response = client.GetAsync(route + "?" + GeneralTags.COMPANY_REF + "=" + ApplicationObject.CompanyRef).Result)
{
if (response.IsSuccessStatusCode)
{
ApplicationObject.PrintData = JsonConvert.DeserializeObject<Model.Print>(response.Content.ReadAsStringAsync().Result);
}
else
{
evError(new Exception(String.Format("{0}: {1}", (int)response.StatusCode, response.ReasonPhrase)), ErrorTags.PRINT_GET);
}
}
}
}
}
then the application exists out.
I may be mistaken but is it because I am using nested async methods?
This is an example of what a thread should look like,
public sealed class StartupTask : IBackgroundTask
{
//has to be declared here to keep the handle alive and prevent garbage collection
private ServerWorkers.WebServer server = new ServerWorkers.WebServer();
public async void Run(IBackgroundTaskInstance taskInstance)
{
//Start the server running no need for await as its an synchronous
server.Start();
//don't exit until work is compelted
while(server.Running)
{
//give up processor and allow other work to occur while you are waiting
await Task.Yield();
}
}
internal class WebServer
{
private const uint BufferSize = 8192;
private StreamSocketListener listener;
public bool Running { get; private set;}= false;
public void Start()
{
Lock(this){//prevent any other code interupting
if(!Running )//prevent multiple starts
{
listener = new StreamSocketListener();
listener.BindServiceNameAsync("8080");
listener.ConnectionReceived += listener_ConnectionReceived;
Running = true;
}
}
}
public void Stop()
{
Lock(this){//prevent any other code interupting
listener.Close();
listener.Dispose();
listener = null;
Running = false;
}
}
public void listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
//process data from listerner's event
}
}
}
Note i'm not using the Windows Application Framework so might be different there
Related
I have a problem: the server doesn't receive any data from the client.
Here is server initialization:
public void Start()
{
var listener = new TcpListener(IPAddress.Any, Port);
listener.Start();
Task.Run(
async () =>
{
while (!this.cancellationToken.IsCancellationRequested)
{
var client = await listener.AcceptTcpClientAsync();
var stream = client.GetStream();
string request = await ReceiveRequestAsync(stream);
await RequestHandlerAsync(request, stream);
}
listener.Stop();
}, this.cancellationToken);
}
Here is requesting client code (it is from unit test so server is initialized right here):
var server = new SimpleFtpServer();
server.Start();
using (TcpClient client = new TcpClient(RequestUri, Port))
{
NetworkStream stream = client.GetStream();
StreamWriter writer = new StreamWriter(stream)
{
AutoFlush = true,
};
writer.Write("zapros");
using (StreamReader reader = new StreamReader(stream))
{
Console.Writeline(reader.ReadToEnd());
}
}
server.Stop();
It worth saying that I have started learning async/await in C# really recently so probably the problem is in usage of them.
Thank you in advance!
its probably not perfect however I am in the same situation as you and created a Async TCP Client/Server for practice and experimentation.
The below is an excerpt of my implementation, it works s
Server:
public class AsyncServerDemo
{
private CancellationTokenSource cancel;
private readonly TcpListenerEx listener;
private Task WaitingForConnections;
private Timer timerCallAcceptClients;
public bool IsRunning { get; private set; }
public AsyncServerDemo(int port)
{
cancel = new CancellationTokenSource();
listener = new TcpListenerEx(IPAddress.Any, port);
}
private Task<string> WaitForMessageAsync(TcpClient client, CancellationToken token)
{
return Task.Run(() =>
{
StringBuilder sb = new StringBuilder();
bool dataAvailable = false;
while (!token.IsCancellationRequested)
{
while (client.Client.Available > 0)
{
dataAvailable = true;
int buffered = client.Client.Available;
byte[] buffer = new byte[buffered];
client.Client.Receive(buffer);
sb.Append(Encoding.ASCII.GetString(buffer));
}
if (dataAvailable)
{
dataAvailable = false;
return sb.ToString();
}
};
return string.Empty; //timeout
});
}
private Task AcceptClientAsync()
{
return Task.Factory.StartNew(async () =>
{
IsRunning = true && !cancel.IsCancellationRequested;
while (!cancel.IsCancellationRequested)
{
if (!listener.Pending())
{
continue;
}
TcpClient newClient = await listener.AcceptTcpClientAsync().ConfigureAwait(false);
Stopwatch timeout = new Stopwatch();
timeout.Restart();
string message = await WaitForMessageAsync(newClient, new CancellationTokenSource(TimeSpan.FromSeconds(5)).Token);
if (message != null)
{
//TODO: Message recieved
}
timeout.Stop();
}
});
}
public void Start()
{
listener.Start();
timerCallAcceptClients = new Timer(new TimerCallback((state) =>
{
AcceptClientAsync();
}), null, 0, (int)TimeSpan.FromSeconds(1).TotalMilliseconds);
}
public async void Stop()
{
if (!IsRunning) return;
using (cancel)
cancel.Cancel();
timerCallAcceptClients.Dispose();
if (WaitingForConnections != null)
await WaitingForConnections;
cancel = null;
listener.Stop();
IsRunning = false;
cancel = new CancellationTokenSource();
}
}
Client:
public class ClientExDemo
{
private Task<string> WaitForMessage;
private NetworkStream currentStream;
private CancellationTokenSource messageToken;
public EventHandler<ClientEx> OnServerFound;
public TcpClient Connection;
public EventHandler<string> OnMessage;
public async Task StartListenAsync(CancellationTokenSource token = null)
{
if (token == null)
messageToken = new CancellationTokenSource();
else
messageToken = token;
currentStream = Connection.GetStream();
string message = "";
if (message.Length > 0)
OnMessage?.Invoke(this, message);
if (!messageToken.IsCancellationRequested)
{
await StartListenAsync(token);
}
Timeout();
}
protected virtual void Timeout()
{
}
public async Task WaitForServerAsync(string ip, int port)
{
do
{
try
{
await Connection.ConnectAsync(ip, port);
}
catch (SocketException x)
{
}
await Task.Delay(50);
} while (!Connection.Connected);
}
public void StopListen()
{
using (messageToken)
{
messageToken.Cancel();
}
try
{
WaitForMessage.GetAwaiter().GetResult();
}
catch (AggregateException)
{
}
currentStream.Close();
messageToken = null;
currentStream = null;
WaitForMessage = null;
}
public ClientExDemo()
{
Connection = new TcpClient();
OnServerFound += ServerFound;
}
private void ServerFound(object sender, ClientEx args)
{
}
public void Send(string message)
{
Connection.Client.Send(Encoding.ASCII.GetBytes(message));
}
}
You can send messages from the client in a simple console application:
ClientEx client= new ClientEx();
await client.WaitForServerAsync(ip, port);
string msg = string.Empty;
do
{
Console.Write("Send Message: ");
msg = Console.ReadLine();
shell.Send(msg);
} while (msg != "q");
Console.WriteLine();
Console.WriteLine("BYE");
Console.ReadKey();
Having below reference code for Async TCP server, I want to pass CancellationToken to OnDataReceived:
public sealed class TcpServer : IDisposable
{
private readonly TcpListener _listener;
private CancellationTokenSource _tokenSource;
private CancellationToken _token;
private bool _listening;
public event EventHandler<ConnectedEventArgs> OnDataReceived;
public TcpServer(IPAddress address, int port)
{
_listener = new TcpListener(address, port);
}
public async Task StartAsync(CancellationToken? token = null)
{
_tokenSource = CancellationTokenSource.CreateLinkedTokenSource(token ?? new CancellationToken());
_token = _tokenSource.Token;
_listener.Start();
_listening = true;
try
{
while (!_token.IsCancellationRequested)
{
await Task.Run(async () =>
{
var tcpClientTask = _listener.AcceptTcpClientAsync();
var tcpClient = await tcpClientTask;
OnDataReceived?.Invoke(tcpClient, new ConnectedEventArgs(tcpClient.GetStream()));
}, _token);
}
}
finally
{
_listener.Stop();
_listening = false;
}
}
public void Stop()
{
_tokenSource?.Cancel();
}
public void Dispose()
{
Stop();
}
}
public class ConnectedEventArgs : EventArgs
{
public NetworkStream Stream { get; private set; }
public ConnectedEventArgs(NetworkStream stream)
{
Stream = stream;
}
}
The following code, shows how I am consuming the above code, currently in ReadStreamBytesAsync I am passing new CancellationToken() instead I want to pass the token argument from MainAsync:
class Program
{
static void Main(string[] args)
{
InitAsyncWork();
Console.WriteLine("ended.");
Console.ReadKey();
}
static void InitAsyncWork()
{
var cts = new CancellationTokenSource();
Console.CancelKeyPress += (s, e) =>
{
e.Cancel = true;
cts.Cancel();
};
MainAsync(cts.Token).GetAwaiter().GetResult();
}
static async Task MainAsync(CancellationToken token)
{
using (var server = new TcpServer(IPAddress.Any, 54001))
{
server.OnDataReceived += TcpClientOnlyReceive;
await server.StartAsync(token);
}
}
private static async void TcpClientOnlyReceive(object sender, ConnectedEventArgs e)
{
try
{
using (TcpClient client = (TcpClient)sender)
using (NetworkStream stream = e.Stream)
{
while (Utilities.IsTcpClientConnected(client))
{
if (client.Available == 0)
{
await Task.Delay(50);
continue;
}
byte[] rawX = await ReadStreamBytesAsync(stream, client.ReceiveBufferSize, new CancellationToken());
}//while(client.Connected)
}//using(client)using(stream)
}
catch (Exception ex)
{
Utilities.logger.Error("TcpClientOnlyReceive():Exception!!\r\nMsg: {1}\r\nStack: {2}", ex.Message, ex.StackTrace);
}
}
private static async Task<byte[]> ReadStreamBytesAsync(NetworkStream stream, int maxBytesToRead, CancellationToken token)
{
var bytesRead = 0;
var totalBytesRead = 0;
var clientMsg = new byte[maxBytesToRead];
byte[] contentBytes;
using (MemoryStream ms = new MemoryStream())
{
do
{
bytesRead = await stream.ReadAsync(clientMsg, totalBytesRead, clientMsg.Length - totalBytesRead, token);
await ms.WriteAsync(clientMsg, totalBytesRead, bytesRead, token);
totalBytesRead += bytesRead;
}
while (bytesRead > 0 && stream.DataAvailable);
contentBytes = ms.ToArray();
}
return contentBytes;
}
}
Should I define cts as global variable? Or modify ConnectedEventArgs class so that it accept CancellationToken as property ?
Clarifications:
Based on the received comments and 1 vote to close the question!
My main objective is to close the application once the user press ctrl+c, currently that's prevent accepting new connections but it won't cancel the established connections.
I never heard of Tasks meant to replace events, if that's true, please share a reference.
It will be great to share better version of the code, if its BAD design! personally I think its clean and robust.
I wrote a client-server app, this is a console chat application for many clients. When only one client is connected, the application works well, but when two or more clients are connected I have a bug, after sending one message to the second client, he lost connection to the server and only first client can send a message to the server...
I used Task for asynchronous operations like listening port and sending messages. When one client sends a message to the server, it adds it to the list messages and resends to all clients to refresh all windows.
Server application:
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Server
{
class Program
{
private static List<Client> clients = new List<Client>();
private static TcpListener listener = null;
private static StreamReader reader = null;
private static StreamWriter writer = null;
private static List<Task> clientTasks = new List<Task>();
private static List<string> messages = new List<string>();
public static void Main()
{
Console.Title = "Server";
try
{
listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8080);
listener.Start();
Console.WriteLine("Server started...");
var connectTask = Task.Run(() => ConnectClients());
//var listenTask = Task.Run(() => ListenClients());
Task.WaitAll(connectTask);
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
if (listener != null)
{
listener.Stop();
}
}
}
private static void ConnectClients()
{
Console.WriteLine("Waiting for incoming client connections...");
while (true)
{
if (listener.Pending()) //if someone want to connect
{
clients.Add(new Client(listener.AcceptTcpClient(), "Client: " + (clients.Count + 1)));
Console.WriteLine(clients[clients.Count - 1].clientName + " connected to server.");
var newClientTask = Task.Run(() => HandleClient(clients[clients.Count - 1]));
clientTasks.Add(newClientTask); //start new task for new client
}
}
}
private static void HandleClient(Client TCPClient)
{
Console.WriteLine("Starting handle client");
string s = string.Empty;
writer = new StreamWriter(TCPClient.client.GetStream());
reader = new StreamReader(TCPClient.client.GetStream());
try
{
while (!(s = reader.ReadLine()).Equals("Exit") || (s == null))
{
if(!TCPClient.client.Connected)
{
Console.WriteLine("Client disconnected.");
clients.Remove(TCPClient);
}
Console.WriteLine("From client: " + TCPClient.clientName + " -> " + s);
messages.Add(TCPClient.clientName + ": " + s); //save new message
//Console.WriteLine(s);
foreach (Client c in clients) //refresh all connected clients
{
c.writer.WriteLine("%C"); //clear client
foreach (string msg in messages)
{
c.writer.WriteLine(msg);
c.writer.Flush();
}
}
}
//CloseServer();
}
catch (Exception e) { Console.WriteLine(e); }
Console.WriteLine("ending handle client");
}
private static void CloseServer()
{
reader.Close();
writer.Close();
clients.ForEach(tcpClient => tcpClient.client.Close());
}
}
}
Client information class:
using System.Net.Sockets;
using System.IO;
namespace Server
{
class Client
{
public TcpClient client;
public StreamWriter writer;
public string clientName;
public Client(TcpClient client, string clientName)
{
this.client = client;
writer = new StreamWriter(client.GetStream());
this.clientName = clientName;
}
}
}
Client application:
using System.Net.Sockets;
using System.Net;
using System.IO;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Client
{
class Program
{
private static TcpClient client = new TcpClient();
private static StreamReader reader;
private static StreamWriter writer;
private static bool refresh;
private static List<string> messages = new List<string>();
public static void Main()
{
Console.Title = "Client";
ConnectLoop();
//Task.WaitAll(sendTask, recieveTask); //wait for end of all tasks
}
private static void ConnectLoop()
{
bool refreshTask = false;
Task sendTask = null, recieveTask = null, updateConvTask = null;
while (true)
{
if(!client.Connected) //try to connect
{
refreshTask = true;
if(sendTask != null || recieveTask != null || updateConvTask != null)
{
sendTask.Dispose();
recieveTask.Dispose();
updateConvTask.Dispose();
sendTask = recieveTask = updateConvTask = null;
}
Console.WriteLine("Connecting to server...");
try
{
client.Connect(IPAddress.Parse("127.0.0.1"), 8080);
}
catch (SocketException) { }
Thread.Sleep(10);
}
else if(refreshTask) // \/ CONNECTED \/
{
Console.WriteLine("Connected.");
reader = new StreamReader(client.GetStream());
writer = new StreamWriter(client.GetStream());
sendTask = Task.Run(() => SendMessage()); //task for sending messages
recieveTask = Task.Run(() => RecieveMessage()); //task for recieving messages
updateConvTask = Task.Run(() => UpdateConversation()); //task for update console window
refreshTask = false;
}
}
}
private static void SendMessage()
{
string msgToSend = string.Empty;
do
{
Console.WriteLine("Enter a message to send to the server");
msgToSend = Console.ReadLine();
writer.WriteLine(msgToSend);
writer.Flush();
} while (!msgToSend.Equals("Exit"));
EndConnection();
}
private static void RecieveMessage()
{
try
{
while (client.Connected)
{
//Console.Clear();
string msg = reader.ReadLine();
if(msg != string.Empty)
{
if (msg == "%C") //special message from server, clear messages if recieve it
{
messages.Clear();
}
else
{
messages.Add(msg);
refresh = true; //refresh console window
}
}
//Console.Clear();
//Console.WriteLine(msgFromServer);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private static void UpdateConversation()
{
//string conversationTmp = string.Empty;
try
{
while (true)
{
if (refresh) //only if refresh
{
refresh = false;
Console.Clear();
messages.ForEach(msg => Console.WriteLine(msg)); //write all messages
Console.WriteLine();
}
}
}
catch (Exception) { }
}
private static void EndConnection()
{
reader.Close();
writer.Close();
client.Close();
}
}
}
I know that my bug will be something stupid. I'm new to TCP/IP applications, could you give me links to some tutorials that use it and Tasks?
Thanks for any help.
By going through some samples, I referred to Polling Service - C# for my polling.
This is my code.
public partial class Service1 : ServiceBase
{
private readonly PollingService _pollingService = new PollingService();
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_pollingService.StartPolling();
}
protected override void OnStop()
{
_pollingService.StopPolling();
}
}
public class PollingService
{
private Thread _workerThread;
private AutoResetEvent _finished;
private const int _timeout = 60 * 1000;
string command = "5120000000000000000000000000000";
public void StartPolling()
{
_workerThread = new Thread(Poll);
_finished = new AutoResetEvent(false);
_workerThread.Start();
}
private void Poll()
{
while (!_finished.WaitOne(_timeout))
{
//do the task
using (TcpClient newclient = new TcpClient())
{
IAsyncResult ar = newclient.BeginConnect("192.168.0.151", 4000, null, null);
if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), false))
{
return;
}
NetworkStream ns = newclient.GetStream();
byte[] outbytes = HexStringToByteArray(command);
ns.Write(outbytes, 0, outbytes.Length);
}
}
}
public void StopPolling()
{
_finished.Set();
_workerThread.Join();
}
public static byte[] HexStringToByteArray(string hexString)
{
if (hexString.Length % 2 > 0)
{
throw new Exception("Invalid command.");
}
byte[] result = new byte[hexString.Length / 2];
try
{
for (int i = 0; i < result.Length; i++)
{
result[i] = Convert.ToByte(hexString.Substring(2 * i, 2), 16);
}
}
catch (Exception)
{
throw;
}
return result;
}
}
I've managed to install. However, when I'm trying to start the service, I'm getting Windows could not start the service on Local Computer. Error 5: Access is denied. I've tried using the solutions given here, Error 5 : Access Denied when starting windows service, however, it is not working.
I found the solution by changing the service properties from This Account to Local System Account with some updated codes.
using (TcpClient newclient = new TcpClient("192.168.0.151", 4000))
{
NetworkStream ns = newclient.GetStream();
byte[] outbytes = Encoding.ASCII.GetBytes(command);
ns.Write(outbytes, 0, outbytes.Length);
ns.Close();
newclient.Close();
}
I have problem with HttpListenerResponse class when client close connection I can´t copy response to outputStream it is logical because stream is interrupted. Is there some easy way how can fix it or handle this exceptions. I know HttpListener is not best solution for proxy server.
I try set up property IgnoreWriteExceptions on true but It´s not working.
public class Ask
{
private int requestCounter = 0;
private ManualResetEvent stopEvent = new ManualResetEvent(false);
public class HttpListenerCallbackState
{
private readonly HttpListener _listener;
private readonly System.Threading.AutoResetEvent _listenForNextRequest;
public HttpListenerCallbackState(HttpListener listener)
{
if (listener == null) throw new ArgumentNullException("listener");
_listener = listener;
_listenForNextRequest = new AutoResetEvent(false);
}
public HttpListener Listener { get { return _listener; } }
public AutoResetEvent ListenForNextRequest { get { return _listenForNextRequest; } }
}
public void ListenAsynchronously(IEnumerable<string> prefixes)
{
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.IgnoreWriteExceptions = true;
listener.Start();
HttpListenerCallbackState state = new HttpListenerCallbackState(listener);
ThreadPool.QueueUserWorkItem(Listen, state);
}
public void StopListening()
{
stopEvent.Set();
}
private void Listen(object state)
{
HttpListenerCallbackState callbackState = (HttpListenerCallbackState)state;
while (callbackState.Listener.IsListening)
{
callbackState.Listener.BeginGetContext(new AsyncCallback(ListenerCallback), callbackState);
int n = WaitHandle.WaitAny(new WaitHandle[] { callbackState.ListenForNextRequest, stopEvent });
if (n == 1)
{
// stopEvent was signalled
callbackState.Listener.Stop();
break;
}
}
}
private void ListenerCallback(IAsyncResult ar)
{
HttpListenerCallbackState callbackState = (HttpListenerCallbackState)ar.AsyncState;
HttpListenerContext context = null;
int requestNumber = Interlocked.Increment(ref requestCounter);
try
{
context = callbackState.Listener.EndGetContext(ar);
}
catch (Exception ex)
{
return;
}
finally
{
callbackState.ListenForNextRequest.Set();
}
if (context == null) return;
HttpListenerRequest request = context.Request;
// add Proxy and network credentials
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(request.Url.AbsoluteUri);
// get response
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
Stream responseOut = context.Response.OutputStream;
int CopyByte = CopyStream(response, responseOut);
responseOut.Close();
}
}
}