QueueUtil.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using ChatServer.util;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Net.Sockets;
  5. using System.Threading;
  6. namespace ChatServer
  7. {
  8. class QueueUtil
  9. {
  10. private static ConcurrentQueue<Item> cq = new ConcurrentQueue<Item>();
  11. public static void Enqueue(Item state)
  12. {
  13. Console.WriteLine("enqueue state...");
  14. cq.Enqueue(state);
  15. }
  16. public static void StartDetecting()
  17. {
  18. Thread queueDetectingThread = new Thread(() =>
  19. {
  20. Console.WriteLine("Run Detecting queue...");
  21. Item item;
  22. while (true)
  23. {
  24. if (cq.TryDequeue(out item))
  25. {
  26. ThreadPool.QueueUserWorkItem(ProcessItem, item);
  27. item = null;
  28. }
  29. }
  30. });
  31. queueDetectingThread.Start();
  32. }
  33. // 메시지를 콘솔에 출력하고 클라이언트에게 돌려줌
  34. static void ProcessItem(object _item)
  35. {
  36. Item item = _item as Item;
  37. Socket clientSocket = item.State.workSocket;
  38. string message = item.Message;
  39. try
  40. {
  41. Console.WriteLine("<Dequeued Item>: {0}", message);
  42. if (clientSocket.Connected)
  43. {
  44. clientSocket.Send(item.Packet);
  45. if (item.Message.Equals(Constants.EXIT))
  46. {
  47. Console.WriteLine("연결 종료 요청...");
  48. clientSocket.Shutdown(SocketShutdown.Both);
  49. clientSocket.Close();
  50. }
  51. }
  52. }
  53. catch (Exception e)
  54. {
  55. Console.WriteLine(e);
  56. clientSocket.Shutdown(SocketShutdown.Both);
  57. clientSocket.Close();
  58. }
  59. }
  60. }
  61. }