Advertisement
Guest User

Untitled

a guest
Apr 27th, 2015
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.47 KB | None | 0 0
  1. bool sended = false;
  2. // PrepairSendingMesage();
  3. Console.WriteLine("Recieving...");
  4. while (true)
  5. {
  6. Console.WriteLine(">>>Waite....");
  7. if (!sended)
  8. {
  9. PrepairSendingMesage();
  10. sended = true;
  11. }
  12.  
  13. StartListen();
  14. }
  15.  
  16. void StartListen()
  17. {
  18. while (true)
  19. {
  20. if (socketClient != null && socketClient.Connected)
  21. {
  22. ReceiveMessage();
  23. }
  24. }
  25. }
  26.  
  27. void ReceiveMessage()
  28. {
  29. try
  30. {
  31.  
  32. byte[] sizeinfo = new byte[4];
  33.  
  34. //read the size of the message
  35. int totalread = 0, currentread = 0;
  36. if (socketClient.Poll(10000, SelectMode.SelectRead))
  37. {
  38. currentread = totalread = socketClient.Receive(sizeinfo);
  39. }
  40. else
  41. {
  42. return;
  43. }
  44.  
  45. while (totalread < sizeinfo.Length && currentread > 0)
  46. {
  47. currentread = socketClient.Receive(sizeinfo,
  48. totalread, //offset into the buffer
  49. sizeinfo.Length - totalread, //max amount to read
  50. SocketFlags.None);
  51.  
  52. totalread += currentread;
  53. }
  54.  
  55. int messagesize = 0;
  56. String sizeinfoString = System.Text.Encoding.ASCII.GetString(sizeinfo);
  57.  
  58.  
  59. if (!Int32.TryParse(sizeinfoString, out messagesize))
  60. {
  61. throw new Exception("receive: " + "Unable to parse length :{0}" + sizeinfoString);
  62. }
  63.  
  64.  
  65. byte[] data = new byte[messagesize];
  66.  
  67. //read the first chunk of data
  68. totalread = 0;
  69. currentread = totalread = socketClient.Receive(data,
  70. totalread, //offset into the buffer
  71. data.Length - totalread, //max amount to read
  72. SocketFlags.None);
  73.  
  74. //if we didn't get the entire message, read some more until we do
  75. while (totalread < messagesize && currentread > 0)
  76. {
  77. currentread = socketClient.Receive(data,
  78. totalread, //offset into the buffer
  79. data.Length - totalread, //max amount to read
  80. SocketFlags.None);
  81. totalread += currentread;
  82. }
  83. //TO-DO: Здесь можно организовать очередь
  84.  
  85. //data - текст входящего сообщения
  86. if (data.Count() == 0)
  87. {
  88. Console.WriteLine("Recieving...");
  89. }
  90. else
  91. {
  92. Console.WriteLine("data:n" + data);
  93. }
  94. }
  95. catch (SocketException exc)
  96. {
  97. throw new Exception("receive: "+exc.Message);
  98. }
  99. catch (Exception exc)
  100. {
  101. throw new Exception("receive: " + exc.Message);
  102. }
  103.  
  104.  
  105. }
  106.  
  107. throw new Exception("receive: " + "Unable to parse length :{0}" + sizeinfoString);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement