public static void ReadCallback(IAsyncResult ar) { try { // To force the socket to close if (!_mode) { allDone.Reset(); //return; } String content = String.Empty; // Retrieve the state object and the handler socket // from the asynchronous state object. MovementStateObject state = (MovementStateObject)ar.AsyncState; Socket handler = state.workSocket; // Read data from the client socket. int bytesRead = handler.EndReceive(ar); if (bytesRead > 0) { // There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString( state.buffer, 0, bytesRead)); // Check for end-of-file tag. If it is not there, read // more data. content = state.sb.ToString(); Debug.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content); if (!string.IsNullOrEmpty(content)) { //string path = Path.Combine(_env.WebRootPath, @"Processor\streaming"); // Image file must have been already uploaded to the location //string name = "todo-filename-" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt"; //File.AppendAllText(Path.Combine(path, name), content + "\n"); _hub.Clients.All.SendCoreAsync("ReceiveMessage", new object[] { "Movement: ", content }); state.sb.Clear(); } if (content.IndexOf("<EOF>") == -1) { // Not all data received. Get more. handler.BeginReceive(state.buffer, 0, MovementStateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } // Echo the data back to the client. Send(handler, content); } } catch (Exception ex) { Debug.Print(ex.Message); } }
public static void AcceptCallback(IAsyncResult ar) { // Signal the main thread to continue. try { allDone.Set(); // Get the socket that handles the client request. Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); // Create the state object. MovementStateObject state = new MovementStateObject(); state.workSocket = handler; handler.BeginReceive(state.buffer, 0, MovementStateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } catch (Exception ex) { Debug.Print(ex.Message); } }