Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- bool sended = false;
- // PrepairSendingMesage();
- Console.WriteLine("Recieving...");
- while (true)
- {
- Console.WriteLine(">>>Waite....");
- if (!sended)
- {
- PrepairSendingMesage();
- sended = true;
- }
- StartListen();
- }
- void StartListen()
- {
- while (true)
- {
- if (socketClient != null && socketClient.Connected)
- {
- ReceiveMessage();
- }
- }
- }
- void ReceiveMessage()
- {
- try
- {
- byte[] sizeinfo = new byte[4];
- //read the size of the message
- int totalread = 0, currentread = 0;
- if (socketClient.Poll(10000, SelectMode.SelectRead))
- {
- currentread = totalread = socketClient.Receive(sizeinfo);
- }
- else
- {
- return;
- }
- while (totalread < sizeinfo.Length && currentread > 0)
- {
- currentread = socketClient.Receive(sizeinfo,
- totalread, //offset into the buffer
- sizeinfo.Length - totalread, //max amount to read
- SocketFlags.None);
- totalread += currentread;
- }
- int messagesize = 0;
- String sizeinfoString = System.Text.Encoding.ASCII.GetString(sizeinfo);
- if (!Int32.TryParse(sizeinfoString, out messagesize))
- {
- throw new Exception("receive: " + "Unable to parse length :{0}" + sizeinfoString);
- }
- byte[] data = new byte[messagesize];
- //read the first chunk of data
- totalread = 0;
- currentread = totalread = socketClient.Receive(data,
- totalread, //offset into the buffer
- data.Length - totalread, //max amount to read
- SocketFlags.None);
- //if we didn't get the entire message, read some more until we do
- while (totalread < messagesize && currentread > 0)
- {
- currentread = socketClient.Receive(data,
- totalread, //offset into the buffer
- data.Length - totalread, //max amount to read
- SocketFlags.None);
- totalread += currentread;
- }
- //TO-DO: Здесь можно организовать очередь
- //data - текст входящего сообщения
- if (data.Count() == 0)
- {
- Console.WriteLine("Recieving...");
- }
- else
- {
- Console.WriteLine("data:n" + data);
- }
- }
- catch (SocketException exc)
- {
- throw new Exception("receive: "+exc.Message);
- }
- catch (Exception exc)
- {
- throw new Exception("receive: " + exc.Message);
- }
- }
- throw new Exception("receive: " + "Unable to parse length :{0}" + sizeinfoString);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement