Advertisement
Guest User

Socket Server

a guest
Sep 28th, 2013
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.37 KB | None | 0 0
  1. namespace SocketServer
  2. {
  3. static class Program
  4. {
  5. private const char LengthPrefixDelimiter = ';';
  6. private static AutoResetEvent _flipFlop = new AutoResetEvent(false);
  7.  
  8. static void Main(string[] args)
  9. {
  10. // create a socket
  11. Socket listener = new Socket(AddressFamily.InterNetwork,
  12. SocketType.Stream,
  13. ProtocolType.Tcp);
  14.  
  15. // create a local endpoint
  16. IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
  17. IPEndPoint localEP = new IPEndPoint(ipHostInfo.AddressList.First(), 22222);
  18.  
  19. Console.WriteLine("Local address and port : {0}", localEP);
  20.  
  21. // bind and listen
  22. try
  23. {
  24. listener.Bind(localEP);
  25. listener.Listen(1);
  26.  
  27. while (true)
  28. {
  29. Console.WriteLine("Waiting for the next connection...");
  30.  
  31. // accept the next connection
  32. listener.BeginAccept(AcceptCallback, listener);
  33.  
  34. _flipFlop.WaitOne();
  35. }
  36. }
  37. catch (Exception e)
  38. {
  39. Console.WriteLine(e.ToString());
  40. }
  41.  
  42. listener.Accept();
  43. listener.Listen(1);
  44.  
  45. }
  46.  
  47. private static void AcceptCallback(IAsyncResult ar)
  48. {
  49. // retrieve the listener, accept
  50. var listener = (Socket)ar.AsyncState;
  51. var socket = listener.EndAccept(ar);
  52.  
  53. Console.WriteLine("Connected a client.");
  54.  
  55. // trigger new listen
  56. _flipFlop.Set();
  57.  
  58. // start receiving
  59. var state = new StateObject();
  60. state.Socket = socket;
  61. socket.BeginReceive(state.Buffer,
  62. 0,
  63. StateObject.BufferSize,
  64. 0,
  65. ReceiveCallback,
  66. state);
  67. }
  68.  
  69. private static void ReceiveCallback(IAsyncResult ar)
  70. {
  71. // retrieve the state and socket
  72. StateObject state = (StateObject)ar.AsyncState;
  73. Socket socket = state.Socket;
  74.  
  75. // Read data from the client socket.
  76. int read = socket.EndReceive(ar);
  77.  
  78. // flag to indicate there's more data coming
  79. bool allRead = true;
  80.  
  81. // Data was read from the client socket.
  82. if (read > 0)
  83. {
  84. // convert result and output
  85. string chunk = Encoding.UTF8.GetString(state.Buffer, 0, read);
  86. state.StringBuilder.Append(chunk);
  87.  
  88. // here's our small protocol implementation: check the length-prefix
  89. string messageLengthText = state.StringBuilder.SubstringByDelimiter(LengthPrefixDelimiter);
  90. if (state.TotalSize == 0)
  91. {
  92. if (!string.IsNullOrEmpty(messageLengthText))
  93. {
  94. // get length and set total size
  95. var messageLength = Convert.ToInt32(messageLengthText);
  96. state.TotalSize = messageLength;
  97. }
  98. else
  99. {
  100. // if we haven't received the delimiter yet (very unlikely),
  101. // simply continue reading
  102. allRead = false;
  103. }
  104. }
  105.  
  106. // simply check if we've read all bytes
  107. allRead = allRead && state.StringBuilder.Length - messageLengthText.Length - 1 == state.TotalSize;
  108. }
  109.  
  110. // check if we need to listen again
  111. if (!allRead)
  112. {
  113. // receive again
  114. socket.BeginReceive(state.Buffer,
  115. 0,
  116. StateObject.BufferSize,
  117. 0,
  118. ReceiveCallback,
  119. state);
  120. }
  121. else
  122. {
  123. // output anything we've received
  124. if (state.StringBuilder.Length > 0)
  125. {
  126. // prepare result
  127. string result = state.StringBuilder.ToString();
  128. result = result.Substring(result.IndexOf(LengthPrefixDelimiter) + 1);
  129.  
  130. // output result on console
  131. Console.WriteLine("Received a message: {0}", result);
  132. }
  133.  
  134. socket.Shutdown(SocketShutdown.Both);
  135. socket.Close();
  136. Console.WriteLine("Closed client connection.");
  137. }
  138. }
  139.  
  140. public static string SubstringByDelimiter(this StringBuilder sb, char delimiter)
  141. {
  142. StringBuilder result = new StringBuilder(sb.Length);
  143. for (int i = 0; i < sb.Length; i++)
  144. {
  145. if (sb[i] == delimiter)
  146. {
  147. return result.ToString();
  148. }
  149.  
  150. result.Append(sb[i]);
  151. }
  152.  
  153. return string.Empty;
  154. }
  155. }
  156.  
  157. public class StateObject
  158. {
  159. public Socket Socket;
  160. public StringBuilder StringBuilder = new StringBuilder();
  161. public const int BufferSize = 10;
  162. public byte[] Buffer = new byte[BufferSize];
  163. public int TotalSize;
  164. }
  165. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement