当前位置: 首页>>代码示例>>C#>>正文


C# StateObject类代码示例

本文整理汇总了C#中StateObject的典型用法代码示例。如果您正苦于以下问题:C# StateObject类的具体用法?C# StateObject怎么用?C# StateObject使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


StateObject类属于命名空间,在下文中一共展示了StateObject类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AcceptCallback

        /// <summary>
        /// AcceptCallback是回调函数
        /// </summary>
        /// <param name="ar"></param>
        public static void AcceptCallback(IAsyncResult ar)
        {
            // 接收连接后,按照前面的定义会执行该函数,首先就是让主线程继续往下执行
            allDone.Set();
            count++;
            Console.WriteLine("连接已经建立");

            try
            {
                //将接收的连接传递进来
                Socket listener = (Socket)ar.AsyncState;

                //调用EndAccept方法表示连接已经建立,建立的连接就是该方法的返回的对象
                Socket handler = listener.EndAccept(ar);

                //保存当前会话的Socket信息
                StateObject state = new StateObject();

                state.socket = handler;

                //这里又出现了类似的定义。可以看出,BeginReceive函数的参数和同步里面Receive函数的参数前面是相同的
                //只是后面多出了两个:定义在BeginReceive函数执行完毕以后所要执行的操作
                //这里定义的是ReadCallback函数
                handler.BeginReceive(state.buffer, 0, StateObject.bufferSize, 0,
                    new AsyncCallback(ReadCallback), state);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                _iLog.Error(ex.Message);
            }
        }
开发者ID:Deson621,项目名称:demo,代码行数:37,代码来源:AsyncSocketService.cs

示例2: AcceptCallback

        public void AcceptCallback(IAsyncResult ar)
        {
            // Signal the main thread to continue.
            allDone.Set();

            // Get the socket that handles the client request.
            Socket listener = (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept(ar);
            handler.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);

            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = handler;

            lock (__syncroot)
            {
                if (clients.Count < 2)
                {
                    Console.WriteLine("Accepting client {0}", clients.Count);
                    clients[handler.Handle] = state;
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                }
                else
                {
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }
        }
开发者ID:Zawulon,项目名称:jseverywhere,代码行数:29,代码来源:AsynchronousSocketListener.cs

示例3: AcceptCallback

        public static void AcceptCallback(IAsyncResult ar)
        {
            // Signal the main thread to continue.
            AllDone.Set();

            // Get the socket that handles the client request.
            Socket listener = (Socket) ar.AsyncState;
            Socket handler = listener.EndAccept(ar);

            // Create the state object.
            bool wasLoogedIn = false;
            foreach (var stateObject in Clients)
            {
                if ((stateObject.WorkSocket.RemoteEndPoint as IPEndPoint).Address.Address ==
                    (handler.RemoteEndPoint as IPEndPoint).Address.Address)
                {
                    wasLoogedIn = true;
                    ClientState = stateObject;
                    ClientState.WorkSocket = handler;
                    break;
                }
            }
            if (!wasLoogedIn)
            {
                ClientState = new StateObject();
                ClientState.WorkSocket = handler;
                Clients.Add(ClientState);
            }
            handler.BeginReceive(ClientState.Buffer, 0, StateObject.BufferSize, 0,
                                 ReadCallback, ClientState);
        }
开发者ID:ryselis,项目名称:viktoro_viktorina,代码行数:31,代码来源:Server.cs

示例4: Receive

        public void Receive()
        {
            try
            {
                connectDone.WaitOne();
                Console.WriteLine("Start to Listening");
                while (true)
                {
                    receiveDone.Reset();

                    // Create the state object.
                    StateObject state = new StateObject();
                    state.workSocket = server;

                    // Begin receiving the data from the remote device.
                    server.BeginReceive(state.recBuffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReceiveCallback), state);

                    receiveDone.WaitOne();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
开发者ID:TheProjecter,项目名称:somscode,代码行数:26,代码来源:Program.cs

示例5: OnReceive

 public void OnReceive(IAsyncResult asyncResult)
 {
     try
     {
         Console.WriteLine("Got some data...");
         StateObject so = (StateObject)asyncResult.AsyncState;
         Socket s = so.workSocket;
         IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
         EndPoint tempRemoteEP = (EndPoint)sender;
         int read = s.EndReceiveFrom(asyncResult, ref tempRemoteEP);
         Console.WriteLine("Read is {0}", read);
         if (read > 0)
         {
             StateObject processState = new StateObject();
             processState.endPoint = tempRemoteEP;
             processState.buffer = so.buffer;
             processState.workSocket = s;
             processState.recvSize = read;
             processState.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read));
             ProcessBuffer(processState);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine("Exception occurred in OnReceive {0}", e.Message);
         Console.WriteLine(e.StackTrace);
     }
     finally
     {
         allDone.Set();
     }
 }
开发者ID:wirepair,项目名称:GHAST_priv8,代码行数:32,代码来源:UDPServices.cs

示例6: SyncSocClient

        public SyncSocClient(string _ipAddress, int port, int timeout)
        {
            try
            {
                IPAddress ipAddress = System.Net.IPAddress.Parse(_ipAddress);
                mPort = port;
                remoteEP = new IPEndPoint(ipAddress, mPort);

                mSender = new Socket(AddressFamily.InterNetwork,
                                        SocketType.Stream, ProtocolType.Tcp);

                if (timeout > 0)
                {
                    mSender.ReceiveTimeout = timeout;
                    mSender.SendTimeout = timeout;
                }
                //mSender.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout);

                // The socket will linger for 10 seconds after Socket.Close is called.
                LingerOption lingerOption = new LingerOption(true, 10);

                mSender.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);

                stateObj = new StateObject(mSender);
            }
            catch (Exception e)
            {
                setErrorMessage(e, string.Format("소켓생성Error ip[{0}]/port[{1}]/timeout[{2}]]",_ipAddress,port,timeout));
                Logger.error(e.ToString());
            }
        }
开发者ID:WeDoCrm,项目名称:misc,代码行数:31,代码来源:SocketClient.cs

示例7: OnConnectAsync

        private async Task OnConnectAsync(TcpClient tcpClient, StateObject tcpState)
        {
            // Start a transfer task
            var transferTask = OnTransferAsync(tcpClient, tcpState);

            // lock it as this is critial path
            lock (_lock)
                _connections.Add(transferTask);

            try
            {
                await transferTask;

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                lock (_lock)
                    _connections.Remove(transferTask);
            }

        }
开发者ID:quang319,项目名称:Penn-State-Fall,代码行数:25,代码来源:TcpTorrent.cs

示例8: StartListener

        // This method instantiate the tcp server
        public async Task StartListener(StateObject tcpState)
        {
            var TcpServer = TcpListener.Create(1000);

            // this if statement differentiates between a server and a client's server
            if (tcpState.ClientType == false)
            {
                Console.WriteLine("Creating server on port {0}", 1000);
                TcpServer = TcpListener.Create(1000);

            }
            else {
                TcpServer = TcpListener.Create(tcpState.Port);
            }

            TcpServer.Start(100);
            while (true)
            {
                var TcpClient = await TcpServer.AcceptTcpClientAsync();
                var task = OnConnectAsync(TcpClient, tcpState);
                if (task.IsFaulted)
                    task.Wait();
            }
            //Console.WriteLine("Server is closing down");

        }
开发者ID:quang319,项目名称:Penn-State-Fall,代码行数:27,代码来源:TcpTorrent.cs

示例9: AcceptCallback

        public static void AcceptCallback(IAsyncResult ar)
        {
            StateObject state = null;
            TcpServer c = (TcpServer)ar.AsyncState;
            try
            {
                if (c == null) return;
                Socket listener = (Socket)c.m_Socket;
                Socket handler = listener.EndAccept(ar);
                c.onConnect(handler);
                state = new StateObject();
                state.s = handler;
                state.c = (TcpServer)c;
                handler.BeginReceive(state.buffer, 0, state.buffer.Length, 0, new AsyncCallback(ReadCallBack), state);

                listener.BeginAccept(new AsyncCallback(AcceptCallback), c);
            }
            catch (System.Exception ex)
            {
                if (state != null)
                {
                    state.c.onClose(state.s);

                    state.s.Dispose();
                }
            }
        }
开发者ID:dream-young-soul,项目名称:soul,代码行数:27,代码来源:TcpServer.cs

示例10: Targets

 public override List<Hex> Targets(StateObject s)
 {
     List<Hex> targets = new List<Hex>();
     s.Caster.Base.Hex.Adjacent(GameControl.gameControl.GridControl.Map).ForEach(h => h.Adjacent(GameControl.gameControl.GridControl.Map).ForEach(he => targets.Add(he)));
     targets.RemoveAll(h => h.Unit != null);
     return targets;
 }
开发者ID:AndersHqst,项目名称:Battle-For-Betelgeuse,代码行数:7,代码来源:UnitCard.cs

示例11: AcceptCallback

        public void AcceptCallback(IAsyncResult ar)
        {
            //System.Threading.Thread.Sleep(100);
            // Signal the main thread to continue.
            allDone.Set();

            // Get the socket that handles the client request.
            Socket listener = (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept(ar);

            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = handler;
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);

            parent.eventFromMainForm += delegate(object sender, SocketEventArgs e)
            {
                if ((((IPEndPoint)handler.RemoteEndPoint).Address.ToString() == e.address) && (handler.Connected))
                {
                    Send(handler, e.programm + "<EOC>");
                    sendDone.WaitOne();
                    Send(handler, e.parameters + "<EOPN>");
                    sendDone.WaitOne();
                    Send(handler, "<SUBMIT>");
                    sendDone.WaitOne();
                }
                else showM("Handler is offline");
            };
        }
开发者ID:red404,项目名称:ARSMonitor,代码行数:30,代码来源:AsyncServer.cs

示例12: StartClient

    public static void StartClient()
    {
        // Connect to a remote device.
        try
        {

            // Establish the remote endpoint for the socket.
            // The name of the
            // remote device is "host.contoso.com".
            //IPHostEntry ipHostInfo = Dns.Resolve("user");
            //IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
            // Create a TCP/IP socket.
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);

            state = new StateObject();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
开发者ID:yangwenlong,项目名称:ywl,代码行数:25,代码来源:Client.cs

示例13: StartReceiving

        private async Task StartReceiving(StateObject state)
        {
            if (_isDisposed) return;
            if (!_socket.Connected) return;

            _logger.Info("Receiving message...");

            var args = new SocketAsyncEventArgs();
            args.SetBuffer(new byte[0x1000], 0, 0x1000);
            var awaitable = new SocketAwaitable(args);

            while (true)
            {
                await _socket.ReceiveAsync(awaitable);
                var bytesRead = args.BytesTransferred;
                if (bytesRead <= 0) break;

                _logger.Info(string.Format("Bytes read: {0}", bytesRead));
                if (awaitable.EventArgs.Buffer[0] == _framingProtocol.StartFrame || state.StartedReceiving)
                {
                    state.Append(Encoding.ASCII.GetString(awaitable.EventArgs.Buffer, 0, bytesRead));
                }

                if (awaitable.EventArgs.Buffer[bytesRead - 1] == _framingProtocol.EndFrame) // We're done
                {
                    InvokeMessageReceived(state.ToString());
                }
            }
        }
开发者ID:solidgranite,项目名称:AsyncAwaitSocket,代码行数:29,代码来源:InboundSocketProxy.cs

示例14: bomba1_DoWork

        private void bomba1_DoWork(object sender, DoWorkEventArgs e)
        {
            Socket listener = new Socket(
                AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp
            );

            String data = null;

            listener.Bind(bomba1EndPoint);
            listener.Listen(1);

            // Create the state object.
            sBomba1 = new StateObject();
            sBomba1.bomba = bomba1;
            sBomba1.workSocket = listener;

            while (true)
            {
                listener.Accept();
                bomba1Status.Text = "Bomba 1 conectada";

                while (true)
                {
                    int bytesRec = listener.Receive(sBomba1.buffer);
                    data += Encoding.ASCII.GetString(sBomba1.buffer, 0, bytesRec);
                    bomba1.ReportProgress(1, sBomba1);
                }
            }
        }
开发者ID:davividal,项目名称:sistema-bomba,代码行数:31,代码来源:Caixa.cs

示例15: Setup

 public void Setup(StateObject s, SpellCard target, float delay)
 {
     this.s = s;
     this.target = target;
     this.delay = delay;
     invoked = true;
 }
开发者ID:AndersHqst,项目名称:Battle-For-Betelgeuse,代码行数:7,代码来源:SpellCardCallBack.cs


注:本文中的StateObject类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。