Пример #1
0
        private static void OnAcceptProc(IAsyncResult ar)
        {
            if (Listener == null)
            {
                throw new Exception("Not Exists Server object");
            }

            if (Listener != null)
            {
                try
                {
                    Socket handler = Listener.EndAccept(ar);

                    byte[] buf = new byte[256];

                    var wrapObject = new WrapObject
                    {
                        Handler = handler,
                        Buffer  = buf
                    };

                    if (handler != null)
                    {
                        handler.BeginReceive(buf, 0, buf.Length, SocketFlags.None, asyncReceive, wrapObject);
                    }

                    Listener.BeginAccept(asyncAccept, null);
                }
                catch (SocketException e) { }
            }
        }
Пример #2
0
        private static void OnReceiveProc(IAsyncResult ar)
        {
            var wrapObject = ar.AsyncState as WrapObject;

            Socket     handler        = wrapObject.Handler;
            IPEndPoint remoteEndPoint = (IPEndPoint)handler.RemoteEndPoint;

            byte[] buf = wrapObject.Buffer;

            if (handler == null)
            {
                throw new Exception("Not Exists Handler object");
            }

            if (handler != null)
            {
                try
                {
                    int count = handler.EndReceive(ar);
                    if (count > 0)
                    {
                        string msg = Encoding.UTF8.GetString(buf, 0, count);

                        AcceptEventArgs e = new AcceptEventArgs(remoteEndPoint, msg);
                        Accepted?.Invoke(typeof(AcceptServer), e);
                    }

                    wrapObject = new WrapObject
                    {
                        Handler = handler,
                        Buffer  = new byte[256]
                    };

                    handler.BeginReceive(buf, 0, buf.Length, SocketFlags.None, asyncReceive, wrapObject);
                }
                catch (SocketException e) { }
            }
        }