Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Net;
- using System.Net.Sockets;
- using log4net;
- using System.Threading.Tasks;
- using System.Threading;
- using System.Text;
- namespace wServer.networking
- {
- //hackish code
- public class StateObject
- {
- public Socket workSocket = null;
- public Client parent = null;
- public const int bufferSize = 1024;
- public byte[] buffer = new byte[bufferSize];
- }
- internal class NetworkHandler : IDisposable
- {
- Socket handler;
- private static readonly ILog log = LogManager.GetLogger(typeof(NetworkHandler));
- public NetworkHandler(Client parent, Socket skt)
- {
- handler = skt;
- StateObject state = new StateObject();
- state.workSocket = handler;
- state.parent = parent;
- handler.BeginReceive(state.buffer, 0, StateObject.bufferSize, 0,
- new AsyncCallback(ReadCallback), state);
- }
- public static void ReadCallback(IAsyncResult ar)
- {
- String content = String.Empty;
- StateObject state = (StateObject)ar.AsyncState;
- Socket handler = state.workSocket;
- int bytesRead = handler.EndReceive(ar);
- if (bytesRead > 0)
- {
- if (bytesRead < 5)
- {
- state.parent.Disconnect();
- return;
- }
- Packet packet = null;
- try
- {
- packet = Packet.Packets[(PacketID)state.buffer[4]].CreateInstance();
- }
- catch
- {
- log.ErrorFormat("Packet ID not found: {0}", state.buffer[4]);
- }
- packet.Read(state.parent, state.buffer, 0, state.buffer.Length);
- if (state.parent.IsReady())
- {
- state.parent.Manager.Network.AddPendingPacket(state.parent, packet);
- }
- }
- }
- public static void SendPacket(Socket handler, Packet pkt)
- {
- handler.BeginSend(new byte[StateObject.bufferSize], 0, StateObject.bufferSize, 0,
- new AsyncCallback(SendCallback), handler);
- }
- public static void SendCallback(IAsyncResult ar)
- {
- try
- {
- Socket handler = (Socket)ar.AsyncState;
- int bytesSent = handler.EndSend(ar);
- Console.WriteLine("Sent {0} bytes to client.", bytesSent);
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- }
- public void Dispose()
- {
- handler.Shutdown(SocketShutdown.Both);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement