Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. public bool StartListening(string ipAddress, int port)
  2. {
  3. Task.Run(() =>
  4. {
  5. _canceller = new CancellationTokenSource();
  6.  
  7. _backingTcpListener = new TcpListener(IPAddress.Parse(ipAddress), port);
  8. _backingTcpListener.Start();
  9.  
  10. WaitForConnections(_canceller.Token);
  11. });
  12.  
  13. return true;
  14. }
  15.  
  16. private void WaitForConnections(CancellationToken cancelToken)
  17. {
  18. Task.Factory.StartNew(async () =>
  19. {
  20. while (!cancelToken.IsCancellationRequested)
  21. {
  22. var inner = await Task.Run(() =>
  23. {
  24. try
  25. {
  26. return _backingTcpListener.AcceptTcpClient();
  27. }
  28. catch (SocketException)
  29. {
  30. // this will be caused by StopListeningAsync
  31. return null;
  32. }
  33. }, cancelToken);
  34.  
  35. if (inner == null)
  36. {
  37. // null will be returned when the SocketException is caught above
  38. return;
  39. }
  40.  
  41. var outer = new TcpSocketClient(inner, _bufferSize);
  42.  
  43. var args = new TcpSocketConnectionReceivedEventArgs(outer);
  44.  
  45. ConnectionReceived?.Invoke(args);
  46. }
  47. }, cancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Default);
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement