Example #1
0
        void Accept()
        {
            if (SocketAsynPool.Count > 0)
            {
                SocketAsyncEventArgs sockasyn = SocketAsynPool.Pop();
                sockasyn.Completed += new EventHandler <SocketAsyncEventArgs>(WorkaroundCallback);


                if (!Sock.AcceptAsync(sockasyn))
                {
                    WorkaroundCallback(null, sockasyn);
                }

                var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                if (myEnd.Address == IPAddress.Any)
                {
                    client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), myEnd.Port));
                }
                else
                {
                    client.Connect(myEnd);
                }
                client.Close();
            }
            else
            {
                LogOutEvent(null, LogType.Error, "The MaxUserCout");
            }
        }
Example #2
0
        public void SendData(byte[] data)
        {
            Client_Data tmp = new Client_Data();

            tmp.Data = data;
            Sock.BeginSendData(BufferFormat.FormatFCA(tmp));
        }
Example #3
0
        public void Dispose()
        {
            try
            {
                OnClosed(Guid);

                Stream.Close();
                Stream.Dispose();

                Sock.Close();
                Sock.Dispose();

                clientThread.Abort();
                clientThread.Join();
            }
            catch (ThreadAbortException ex)
            {
                string exMsg = string.Empty;

                exMsg = System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name + ":" +
                        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + ex.StackTrace + Environment.NewLine +
                        System.Reflection.MethodBase.GetCurrentMethod().Name + "():" + ex.Message;
                Console.WriteLine("THREAD ABORT ERROR :: " + exMsg);
            }
            catch (Exception ex)
            {
                string exMsg = string.Empty;

                exMsg = System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name + ":" +
                        System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "." + ex.StackTrace + Environment.NewLine +
                        System.Reflection.MethodBase.GetCurrentMethod().Name + "():" + ex.Message;
                Console.WriteLine("Dispose ERROR :: " + exMsg);
            }
        }
Example #4
0
        private async Task ConnectInternalAsync(IPEndPoint ip)
        {
            if (Sock.Connected)
            {
                Sock.Disconnect(true);
                Stream = null;
                Reader = null;
            }

#if NETCOREAPP
            await Sock.ConnectAsync(ip);
#else
            var tcs = new TaskCompletionSource <bool>();
            var sae = new SocketAsyncEventArgs();
            sae.RemoteEndPoint = ip;
            sae.Completed     += (s, e) =>
            {
                tcs.SetResult(true);
            };

            if (Sock.ConnectAsync(sae))
            {
                await tcs.Task;
            }
#endif
            Stream = new NetworkStream(Sock);
            Reader = new StreamReader(Stream, Encoding.UTF8, false, 1024, true);
        }
Example #5
0
        private void DataSent(IAsyncResult res)
        {
            try
            {
                if (!IsConnected())
                {
                    Disconnect();
                    return;
                }

                var sent = ((Socket)res.AsyncState).EndSend(res);
                if (sent < 0)
                {
                    Sock.Shutdown(SocketShutdown.Both);
                    Sock.Close();
                    return;
                }

                var data = new DataEventArgs(this, new byte[] { }, sent);
                OnDataSent(this, data);
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(ex.ToString());
#endif
            }
        }
        public void Close()
        {
            // 중복 수행을 막는다.
            if (Interlocked.CompareExchange(ref this.IsClosed, 1, 0) == 1)
            {
                return;
            }

            if (CurrentState == STATE_CLOSED)
            {
                // already closed.
                return;
            }

            CurrentState          = STATE_CLOSED;
            ReserveClosingMillSec = 0;

            Sock.Close();
            Sock = null;

            SendEventArgs.UserToken    = null;
            ReceiveEventArgs.UserToken = null;

            SendingList.Clear();

            OnSessionClosed(this);

            var msg = new Packet(this, (UInt16)NetworkDefine.SYS_NTF_CLOSED);

            Dispatcher.IncomingPacket(true, this, msg);
        }
Example #7
0
        public async Task <RPCResponse> SendAndWait(RPC c)
        {
            var cts = new CancellationTokenSource();

            cts.CancelAfter(TimeSpan.FromSeconds(30));

            var tcs = new TaskCompletionSource <RPCResponse>();

            cts.Token.Register(() =>
            {
                tcs.SetCanceled();
            });
            var nid = Interlocked.Increment(ref CommandId);

            c.id = nid;

            if (CommandQueue.TryAdd(nid, tcs))
            {
                await Sock.Send(c);

                return(await tcs.Task);
            }
            else
            {
                Console.WriteLine("Failed to add command, skipping..");
            }
            return(default);
Example #8
0
        /// <summary>
        /// 비동기 전송을 시작한다.
        /// </summary>
        void StartSend()
        {
            if (IsConnected() == false)
            {
                return;
            }

            try
            {
                SetSendEventArgsBufferList(SendingList, SendEventArgs.BufferList);

                // 비동기 전송 시작.
                bool pending = Sock.SendAsync(SendEventArgs);
                if (!pending)
                {
                    ProcessSend(SendEventArgs);
                }
            }
            catch (Exception e)
            {
                SetReserveClosing(ServerOpt.ReserveClosingWaitMilliSecond);

                Console.WriteLine("send error!! close socket. " + e.Message);
                throw new Exception(e.Message, e);
            }
        }
Example #9
0
    // Used to get the next Sock to spawn
    public Sock PopRhythmQueue(SongProfiler.PlayerNumber playerNumber)
    {
        Sock sock = null;

        if (playerNumber == SongProfiler.PlayerNumber.Player1)
        {
            if (playerOneSocks.rhythmQueue.Count == 0)
            {
                QueueSock(SongProfiler.PlayerNumber.Player1);
            }
            sock = playerOneSocks.rhythmQueue[0];
            playerOneSocks.rhythmQueue.Remove(sock);
        }

        if (playerNumber == SongProfiler.PlayerNumber.Player2)
        {
            if (playerTwoSocks.rhythmQueue.Count == 0)
            {
                QueueSock(SongProfiler.PlayerNumber.Player2);
            }
            sock = playerTwoSocks.rhythmQueue[0];
            playerTwoSocks.rhythmQueue.Remove(sock);
        }

        return(sock);
    }
Example #10
0
        private void AcceptCallback(IAsyncResult asyncResult)
        {
            Socket socket = null;

            try
            {
                socket = Sock.EndAccept(asyncResult);
            }
            catch (ObjectDisposedException) { return; }
            catch (Exception ex)
            {
                EventProvider.ExecuteErrorHandler(ex, SocketErrorLocation.EndStart);
                return;
            }

            TcpReceiveSocket receiveSocket = new TcpReceiveSocket(socket, SocketSide.Client, EventProvider);

            if (receiveSocket.Start())
            {
                TcpClientSockets.Add(receiveSocket);
                TcpClientSockets.TrimExcess();
            }

            EventProvider.ExecuteHandshakeHandler(((IPEndPoint)socket.RemoteEndPoint).Address, receiveSocket);

            Sock.BeginAccept(AcceptCallback, null);
        }
Example #11
0
    // Get the first sock of a Player
    public Sock PopPlayerSock(SongProfiler.PlayerNumber playerNumber)
    {
        Sock sock = null;

        if (playerNumber == SongProfiler.PlayerNumber.Player1)
        {
            if (playerOneSocks.playerQueue.Count == 0)
            {
                QueueSock(SongProfiler.PlayerNumber.Player1);
            }
            sock = playerOneSocks.playerQueue[0];
            playerOneSocks.playerQueue.Remove(sock);
        }

        if (playerNumber == SongProfiler.PlayerNumber.Player2)
        {
            if (playerTwoSocks.playerQueue.Count == 0)
            {
                QueueSock(SongProfiler.PlayerNumber.Player2);
            }
            sock = playerTwoSocks.playerQueue[0];
            playerTwoSocks.playerQueue.Remove(sock);
        }

        availableSocks.Add(sock);

        return(sock);
    }
Example #12
0
        void Receive()
        {
            ReceiveThread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            {
                while (true)
                {
                    System.Threading.WaitHandle.WaitAll(reset);
                    reset[0].Set();

                    if (SocketAsynPool.Count > 0)
                    {
                        SocketAsyncEventArgs sockasyn = SocketAsynPool.Pop();

                        if (BuffManagers.SetBuffer(sockasyn))
                        {
                            if (!Sock.ReceiveFromAsync(sockasyn))
                            {
                                BeginReceive(sockasyn);
                            }
                        }
                    }
                    else
                    {
                        reset[0].Reset();
                    }
                }
            }));

            ReceiveThread.Start();
        }
Example #13
0
        internal void PostRecv()
        {
            IAsyncResult ar           = null;
            SocketError  socketError  = SocketError.SocketError;
            HandlerParam handlerParam = null;

            try
            {
                handlerParam = new HandlerParam(EHandlerType.Socker, this);
                if (LOG_ERROR(handlerParam != null))
                {
                    goto Exit0;
                }

                ar = Sock.BeginReceive(RecvBuf.BufBytes, RecvBuf.WriteInx, RecvBuf.GetOnceWritableLen(), SocketFlags.None, out socketError,
                                       LP.NetModule.Reactor.OnReceive, handlerParam);
                if (socketError != SocketError.Success)
                {
                    Close(ESockerCloseType.PostRecvFail, 1, true);
                    goto Exit0;
                }
                if (LOG_ERROR(ar != null))
                {
                    goto Exit0;
                }
            }
            catch (Exception e)
            {
                LPMiniDump.GenerateNormalDump(e);
            }

Exit0:
            return;
        }
Example #14
0
    static bool tcp_check_do(string host, int port, int timeout)
    {
        Sock s = Sock.Connect(host, port, timeout, true, true);

        try
        {
            byte[] d = new byte[1];
            d[0] = (byte)'a';

            int i;
            int num = 3;

            for (i = 0; i < num; i++)
            {
                if (s.SendAll(d) == false)
                {
                    return(false);
                }

                if (i <= (num - 1))
                {
                    ThreadObj.Sleep(300);
                }
            }

            return(true);
        }
        finally
        {
            s.Disconnect();
        }
    }
        public void Send(byte[] datas)
        {
            if (Sock != null && Sock.Connected)
            {
                var args = SocketHelpers.AcquireSocketArg();
                if (args != null)
                {
                    args.Completed += SendAsyncComplete;
                    args.UserToken  = this;
                    args.SetBuffer(datas, 0, datas
                                   .Length);
                    Sock.SendAsync(args);

                    //  Logger.WriteMsg(string.Format("[Send] {0}", message.ToString()), ConsoleColor.DarkGray);
                    unchecked
                    {
                        _bytesSent += (uint)datas.Length;
                    }

                    Interlocked.Add(ref _totalBytesSent, datas.Length);
                }
                else
                {
                }
            }
        }
Example #16
0
        public void Close()
        {
            if (Interlocked.CompareExchange(ref this.IsClosed, 1, 0) == 1)
            {
                return;
            }

            if (CurrentState == State.Closed)
            {
                return;
            }

            CurrentState = State.Closed;
            Sock.Close();
            Sock = null;

            SendEventArgs.UserToken    = null;
            ReceiveEventArgs.UserToken = null;

            SendingList.Clear();
            MsgResolver.ClearBuffer();

            if (Peer != null)
            {
                var msg = Packet.Create((short)-1);
                Dispatcher.IncomingPacket(this, new ArraySegment <byte>(msg.Buffer, 0, msg.Position));
            }
        }
Example #17
0
        public void Close()
        {
            // 중복 수행을 막는다.
            if (Interlocked.CompareExchange(ref this.IsClosed, 1, 0) == 1)
            {
                return;
            }

            if (CurrentState == STATE_CLOSED)
            {
                // already closed.
                return;
            }

            CurrentState          = STATE_CLOSED;
            ReserveClosingMillSec = 0;

            Sock.Close();
            Sock = null;

            SendEventArgs.UserToken    = null;
            ReceiveEventArgs.UserToken = null;

            SendingList.Clear();

            RefMsgResolver.ClearBuffer();


            OnSessionClosed(this);

            var msg = Packet.Create((short)NetworkDefine.SYS_NTF_CLOSED);

            Dispatcher.IncomingPacket(true, this, new ArraySegment <byte>(msg.Buffer, 0, msg.Position));
        }
Example #18
0
        public void ReceiveAsync(int buffersize = -1)
        {
            try
            {
                if (!IsConnected())
                {
                    Disconnect();
                    return;
                }

                if (buffersize > -1)
                {
                    _buffer = new byte[buffersize];
                }
                Receiving = true;
                Sock.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, DataReceived, Sock);
            }
            catch (Exception ex)
            {
                #if DEBUG
                Console.WriteLine(ex.ToString());
                #endif
                Disconnect();
            }
        }
Example #19
0
        public int Receive(byte[] data, int offset, int count)
        {
            try
            {
                if (!IsConnected())
                {
                    Disconnect();
                    return(-1);
                }

                var received = Sock.Receive(data, offset, count, SocketFlags.None);
                if (received <= 0)
                {
                    Disconnect();
                    return(-1);
                }
                var dargs = new DataEventArgs(this, data, received);
                OnDataReceived(this, dargs);
                return(received);
            }
            catch (Exception ex)
            {
                #if DEBUG
                Console.WriteLine(ex.ToString());
                #endif
                Disconnect();
                return(-1);
            }
        }
Example #20
0
        public List <Sock> HashSort(List <Sock> unmatchedSocks)
        {
            Stopwatch watch = new Stopwatch();

            watch.Start();
            List <Sock> matchedSocks = new List <Sock>(unmatchedSocks.Count);

            var waitingForMatch = new Sock[80]; // Colors << 2 (Lengths) << 2 (Owners)

            for (var index = unmatchedSocks.Count - 1; index >= 0; index--)
            {
                var sock = unmatchedSocks[index];
                unmatchedSocks.RemoveAt(index);
                var bucket = ((int)sock.Color << 4) +
                             ((int)sock.Length << 2) +
                             (int)sock.Owner;

                if (waitingForMatch[bucket] != null)
                {
                    matchedSocks.Add(sock);
                    matchedSocks.Add(waitingForMatch[bucket]);
                    waitingForMatch[bucket] = null;
                }
                else
                {
                    waitingForMatch[bucket] = sock;
                }
            }

            watch.Stop();
            Console.WriteLine("Completed Hash Sort in " + watch.ElapsedMilliseconds.ToString() + " milliseconds.");

            return(matchedSocks);
        }
Example #21
0
        private byte[] Receive()
        {
            var  buf  = new byte[4048];
            byte last = 0;

            while (last != 0x05)
            {
                var bytesRead = Sock.Receive(buf, 0, 2048, SocketFlags.None);

                if (bytesRead > 0)
                {
                    last = 0;
                    for (var i = buf.Length - 1; i > 0; i--)
                    {
                        var b = buf[i];
                        if (b != 0x0 && b != 0xA)
                        {
                            last = b;
                            break;
                        }
                    }
                }
            }

            return(buf);
        }
Example #22
0
        public bool Send(byte[] buff, int offset, int count)
        {
            try
            {
                if (!IsConnected())
                {
                    Disconnect();
                    return(false);
                }

                if (Sock.Send(buff, offset, count, SocketFlags.None) <= 0)
                {
                    Disconnect();
                    return(false);
                }
                var data = new DataEventArgs(this, buff, count);
                OnDataSent(this, data);
                return(true);
            }
            catch (Exception ex)
            {
                #if DEBUG
                Console.WriteLine(ex.ToString());
                #endif
                Disconnect();
                return(false);
            }
        }
        private void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            ToastController toastController;
            string          userName = UserNameTextBox.Text;
            string          passWord = PassWordTextBox.Password;

            Sock   sock   = new Sock(userName, passWord, testHost, port);
            Status status = Status.NONE;

            status = sock.Login(userName, passWord);
            if (status == Status.LOGIN_AC)
            {
                //储存到全局变量中
                ConstantVariable.ConstantVariable.sock = sock;
                Frame root = Window.Current.Content as Frame;
                //root.Navigate(typeof(CommunicatePage),sock);
                root.Navigate(typeof(CommunicatePage));
                //sock.start();
            }
            else if (status == Status.WRONG_PASSWORD)
            {
                toastController = new ToastController("Login Failure!Please check the password");
                toastController.Show();
            }
            else if (status == Status.NO_MEMSHIP)
            {
                toastController = new ToastController("No Memship!Please register and try again!");
                toastController.Show();
            }
        }
Example #24
0
 public void Dispose()
 {
     Reader.Dispose();
     Stream.Dispose();
     Sock.Close();
     Sock.Dispose();
     Lock.Dispose();
 }
        private void RegisterButton_Click(object sender, RoutedEventArgs e)
        {
            Sock sock = new Sock(testHost, port);

            Frame root = Window.Current.Content as Frame;

            root.Navigate(typeof(RegisterPage), sock);
        }
Example #26
0
        void tcpAcceptedThread(object?param)
        {
            Sock s = (Sock)param !;

            ThreadObj.NoticeInited();

            this.AcceptProc(this, s, this.AcceptParam);
        }
Example #27
0
        public void Start()
        {
            Sock.Listen(1024);
            AcceptTask        = Accept();
            CheckPeerListTask = CheckPeerList();

            OnLog?.Invoke($"Node Started on {Sock.LocalEndPoint}!");
        }
Example #28
0
 private void Accept(SocketAsyncEventArgs args)
 {
     args.AcceptSocket = null;
     if (!Sock.AcceptAsync(args))
     {
         Asyn_Completed(null, args);
     }
 }
Example #29
0
        private void Send(string data)
        {
            // Convert the string data to byte data using ASCII encoding.
            var byteData = Encoding.ASCII.GetBytes(data + "|");

            // Begin sending the data to the remote device.
            Sock.Send(byteData);
        }
Example #30
0
        private void Loop()
        {
            while (true)
            {
                try
                {
                    byte[] DataLength = new byte[2];
                    Sock.Receive(DataLength);
                    short Length = System.BitConverter.ToInt16(DataLength, 0);

                    byte[] PacketIdentifier = new byte[1];
                    Sock.Receive(PacketIdentifier);

                    byte[] Packet = new byte[Length];
                    Sock.Receive(Packet);

                    if (PacketIdentifier[0] == 0xFF)
                    {
                        //get some shit
                        switch (Packet[0])
                        {
                        case 1:
                            //handshake
                            Handshake();
                            break;

                        default: throw new Exception("Got protocol ID, but is malformed.");
                        }
                    }
                    else
                    {
                        ISComm.EventArgs.OnMessageArgs args = new ISComm.EventArgs.OnMessageArgs();
                        args.ID = PacketIdentifier[0];
                        if (args.ID == 0xFF)
                        {
                            args.IsProtocolPacket = true;
                        }
                        else
                        {
                            args.IsProtocolPacket = false;
                        }
                        args.Data   = Packet;
                        args.Length = (short)(3 + Packet.Length);

                        //now call event handler
                        OnMessage(this, args);
                    }
                }
                catch (ObjectDisposedException)
                {
                    return;
                }
                catch (SocketException)
                {
                    return;
                }
            }
        }
Example #31
0
 private IEnumerator DelayedSockIdSet(Sock _sock, int _id)
 {
     yield return null;
     _sock.SetID (_id);
 }