I run the following code snippet that a delegate uses to return an asynchronous network stream:
static void Main(string[] args) { NetworkStream myNetworkStream; Socket socket; IPEndPoint maxPort = new IPEndPoint(IPAddress.Parse("xxx.xxx.xxx.xxx"), xxxx); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); socket.Connect(maxPort); myNetworkStream = new NetworkStream(socket); byte[] buffer = new byte[1024]; int offset = 0; int count = 1024; string Command = "LOGIN,,,xxxx\n"; ASCIIEncoding encoder = new ASCIIEncoding(); myNetworkStream.BeginRead(buffer, offset, count, new AsyncCallback(OnBeginRead), myNetworkStream); myNetworkStream.Write(encoder.GetBytes(Command), 0, encoder.GetByteCount(Command)); while (true) { } } public static void OnBeginRead(IAsyncResult ar) { NetworkStream ns = (NetworkStream)ar.AsyncState; int bufferSize = 1024; byte[] received = new byte[bufferSize]; ns.EndRead(ar); int read; while (true) { if (ns.DataAvailable) { string result = String.Empty; read = ns.Read(received, 0, bufferSize); result += Encoding.ASCII.GetString(received); received = new byte[bufferSize]; result = result.Replace(" ", ""); result = result.Replace("\0", ""); result = result.Replace("\r\n", ","); Console.WriteLine(result); } } }
It works, but my processor is used through the roof (50% on Intel Core i3), so obviously I'm doing it wrong, but how is it?
thanks
source share