Advertisement
Guest User

Untitled

a guest
May 25th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.92 KB | None | 0 0
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using log4net;
  7. using System.Threading.Tasks;
  8. using System.Threading;
  9. using System.Text;
  10.  
  11. namespace wServer.networking
  12. {
  13. //hackish code
  14.  
  15. public class StateObject
  16. {
  17. public Socket workSocket = null;
  18. public Client parent = null;
  19. public const int bufferSize = 1024;
  20. public byte[] buffer = new byte[bufferSize];
  21. }
  22.  
  23. internal class NetworkHandler : IDisposable
  24. {
  25. Socket handler;
  26. private static readonly ILog log = LogManager.GetLogger(typeof(NetworkHandler));
  27.  
  28. public NetworkHandler(Client parent, Socket skt)
  29. {
  30. handler = skt;
  31. StateObject state = new StateObject();
  32. state.workSocket = handler;
  33. state.parent = parent;
  34. handler.BeginReceive(state.buffer, 0, StateObject.bufferSize, 0,
  35. new AsyncCallback(ReadCallback), state);
  36. }
  37.  
  38. public static void ReadCallback(IAsyncResult ar)
  39. {
  40. String content = String.Empty;
  41.  
  42. StateObject state = (StateObject)ar.AsyncState;
  43. Socket handler = state.workSocket;
  44.  
  45. int bytesRead = handler.EndReceive(ar);
  46.  
  47. if (bytesRead > 0)
  48. {
  49. if (bytesRead < 5)
  50. {
  51. state.parent.Disconnect();
  52. return;
  53. }
  54.  
  55. Packet packet = null;
  56. try
  57. {
  58. packet = Packet.Packets[(PacketID)state.buffer[4]].CreateInstance();
  59. }
  60. catch
  61. {
  62. log.ErrorFormat("Packet ID not found: {0}", state.buffer[4]);
  63. }
  64. packet.Read(state.parent, state.buffer, 0, state.buffer.Length);
  65. if (state.parent.IsReady())
  66. {
  67. state.parent.Manager.Network.AddPendingPacket(state.parent, packet);
  68. }
  69. }
  70. }
  71.  
  72. public static void SendPacket(Socket handler, Packet pkt)
  73. {
  74. handler.BeginSend(new byte[StateObject.bufferSize], 0, StateObject.bufferSize, 0,
  75. new AsyncCallback(SendCallback), handler);
  76. }
  77.  
  78. public static void SendCallback(IAsyncResult ar)
  79. {
  80. try
  81. {
  82. Socket handler = (Socket)ar.AsyncState;
  83.  
  84. int bytesSent = handler.EndSend(ar);
  85. Console.WriteLine("Sent {0} bytes to client.", bytesSent);
  86.  
  87. }
  88. catch (Exception e)
  89. {
  90. Console.WriteLine(e.ToString());
  91. }
  92. }
  93.  
  94. public void Dispose()
  95. {
  96. handler.Shutdown(SocketShutdown.Both);
  97. }
  98. }
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement