code_junkie

How should I handle socket disconnections in .NET

Nov 14th, 2011
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. class ConnectionWrapper {
  2. NetworkStream stream;
  3. StreamReader reader;
  4. Endpoint endPoint;
  5. bool endOfStream;
  6. int maxRetries = 5;
  7.  
  8. public void connect() {
  9. // ... code to initialize a (TCP) socket to endPoint
  10. this.stream = new NetworkStream(socket, true);
  11. this.reader = new StreamReader(stream);
  12. }
  13.  
  14. string readNextMsg() {
  15. try {
  16. string msg = reader.ReadLine();
  17. if (msg == "EOF") endOfStream = true;
  18. return msg;
  19. }
  20. catch (IOException e) {
  21. Exception ex = e;
  22. while (maxRetries-- > 0) {
  23. try { connect(); ex = null; }
  24. catch (Exception e2) { ex = e2; }
  25. }
  26. if (x != null) throw ex;
  27. }
  28. }
  29. }
  30.  
  31. class ConnectionWrapper {
  32. NetworkStream stream;
  33. StreamReader reader;
  34. Endpoint endPoint;
  35. bool endOfStream;
  36. int maxRetries = 5;
  37. ArrayList arr;
  38.  
  39. public void connect() {
  40. // ... code to initialize a (TCP) socket to endPoint
  41. this.stream = new NetworkStream(socket, true);
  42. this.reader = new StreamReader(stream);
  43. }
  44.  
  45. private void initReceiverThread() {
  46. String line;
  47.  
  48. while(stream.isConnected() && (line = reader.readLine()) != null) {
  49. // notify observers of a change
  50. arr.add(line);
  51. }
  52. }
  53. }
  54.  
  55. public ArrayList getMessages() {
  56. ArrayList temp = arr;
  57. arr.clear();
  58. return temp;
  59. }
Add Comment
Please, Sign In to add comment