Beispiel #1
0
        void processClient(IAsyncResult ar)
        {
            server.BeginAcceptTcpClient(processClient, server);

            var client = server.EndAcceptTcpClient(ar);

            System.Diagnostics.Debug.WriteLine("connection from " + client.Client.RemoteEndPoint + " started");
            var stream = client.GetStream();

            using (var reader = new System.IO.StreamReader(stream))
                using (var writer = new System.IO.StreamWriter(stream))
                {
                    string        line    = "";
                    StringBuilder request = new StringBuilder();
                    //process in http style chunks separated by blank lines
                    while (client.Connected && stream.CanRead && null != line)
                    {
                        line = reader.ReadLine();
                        if (line == "" || line == null && request.Length > 0)
                        {
                            dataReceived(request.ToString(), writer);
                            request = new StringBuilder();
                        }
                        else
                        {
                            request.AppendLine(line);
                        }
                    }
                }
            System.Diagnostics.Debug.WriteLine("connection  ended");
        }
Beispiel #2
0
        public static int Queue(byte[] buffer)
        {
            var tcpListener = new System.Net.Sockets.TcpListener(IPAddress.Any, 0);
            var state       = new State {
                Buffer = buffer, TcpListener = tcpListener
            };

            try
            {
                tcpListener.Start();

                int port = ((IPEndPoint)tcpListener.LocalEndpoint).Port;

                ThreadPool.QueueUserWorkItem(_ =>
                {
                    bool listening = true;

                    while (listening)
                    {
                        var handle = tcpListener.BeginAcceptTcpClient(OnIncomingConnection, state);
                        listening  = handle.AsyncWaitHandle.WaitOne(ListenTimeoutMilliseconds);
                    }

                    Cleanup(state);
                });

                return(port);
            }
            catch (Exception)
            {
                Cleanup(state);
                return(-1);
            }
        }
Beispiel #3
0
        /// <summary>
        /// 启动监听
        ///     创建监听线程,启动监听。
        /// </summary>
        public void StartListen()
        {
            if (IsListening)
            {
                return;
            }

            // 创建TcpListener
            ClarifyInfo($"创建TcpListener,监听端口[{ListenPort}]……", 1);
            _TcpListener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, ListenPort);

            // 启动监听
            try
            {
                ClarifyInfo($"启动监听端口[{ListenPort}]……", 1);
                IsListening = true;
                _TcpListener.Start();
            }
            catch (System.Exception ex)
            {
                ClarifyInfo(string.Format("启动监听端口[{0}]发生错误:{1}", ListenPort, ex.Message), 0);
                IsListening = false;
                return;
            }

            // 主工作循环,等待并处理连接请求
            ClarifyInfo(string.Format("开始监听端口[{0}]的主工作过程,等待连接请求……", ListenPort), 1);
            _TcpListener.BeginAcceptTcpClient(_ListenCallback, null);
            IsListening = true;
        }
Beispiel #4
0
        public void AcceptOverStop_TryTcpListener()
        {
            System.Net.Sockets.TcpListener lsnr = null;
            var ep = new System.Net.IPEndPoint(System.Net.IPAddress.Loopback, 0);

            try {
                lsnr = new System.Net.Sockets.TcpListener(ep);
                lsnr.Start();
                var arAccept = lsnr.BeginAcceptTcpClient(null, null);
                // *
                lsnr.Stop();
                TestsApmUtils.SafeNoHangWaitShort(arAccept, "EndAccept");
                try {
                    lsnr.EndAcceptTcpClient(arAccept);
                    Assert.Fail("should have thrown");
                } catch (ObjectDisposedException ex) {
                    Assert.AreEqual(typeof(ObjectDisposedException), ex.GetType());
                }
            } finally {
                if (lsnr != null)
                {
                    lsnr.Stop();
                }
            }
        }
Beispiel #5
0
        public void AcceptAfterStop_TryTcpListener()
        {
            System.Net.Sockets.TcpListener lsnr = null;
            var ep = new System.Net.IPEndPoint(System.Net.IPAddress.Loopback, 0);

            try {
                //-- NO start --
                lsnr = new System.Net.Sockets.TcpListener(ep);
                lsnr.Start();
                // *
                lsnr.Stop();
                try {
                    var arAccept = lsnr.BeginAcceptTcpClient(null, null);
                    Assert.Fail("should have thrown");
                } catch (InvalidOperationException ex) {
                    Assert.AreEqual(typeof(InvalidOperationException), ex.GetType());
                    // System.InvalidOperationException :
                    // "Not listening. You must call the Start() method before calling this method."
                }
            } finally {
                if (lsnr != null)
                {
                    lsnr.Stop();
                }
            }
        }
Beispiel #6
0
 public void Start()
 {
     server = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, Port);
     server.Start();
     //task = System.Threading.Tasks.Task.Factory.StartNew(()=> {while(true) {
     //    server.BeginAcceptTcpClient(processClient, server);
     //}});
     server.BeginAcceptTcpClient(processClient, server);
 }
Beispiel #7
0
        /**
         * Starts accepting connecting clients.
         */
        private void Listen()
        {
            listener.Start();
            OnLog("Awaiting connections...");
            ManualResetEvent wait = new ManualResetEvent(false);

            while (true)
            {
                wait.Reset();
                listener.BeginAcceptTcpClient(AcceptCallback, wait);
                wait.WaitOne();
            }
        }
Beispiel #8
0
        void form_WorkIsDone(object sender, RunWorkerCompletedEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            if (e.Error != null)
            {
                this.BeginInvoke(new MethodInvoker(() => MessageBox.Show(this,
                                                                         e.Error.ToString(),
                                                                         this.Text,
                                                                         MessageBoxButtons.OK,
                                                                         MessageBoxIcon.Error
                                                                         )));
            }

            System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(8000);
            listener.Start(1);
            listener.BeginAcceptTcpClient(ClientConnected, listener);
        }
        static StackObject *BeginAcceptTcpClient_1(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.Object @state = (System.Object) typeof(System.Object).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.AsyncCallback @callback = (System.AsyncCallback) typeof(System.AsyncCallback).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Net.Sockets.TcpListener instance_of_this_method = (System.Net.Sockets.TcpListener) typeof(System.Net.Sockets.TcpListener).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.BeginAcceptTcpClient(@callback, @state);

            return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method));
        }
 public void start(int port)
 {
     server  = new System.Net.Sockets.TcpListener(port);
     server.Start();
     server.BeginAcceptTcpClient(onClientConnect, server);
 }
Beispiel #11
0
 private void ListenForClients()
 {
     _tcpListener.BeginAcceptTcpClient(ClientConnectedCallback, null);
     log.Trace("ready for new connection request");
 }
Beispiel #12
0
        void form_WorkIsDone(object sender, RunWorkerCompletedEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            if (e.Error != null)
            {
                this.BeginInvoke(new MethodInvoker(() => MessageBox.Show(this,
                    e.Error.ToString(),
                    this.Text,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                    )));
            }

            System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(8000);
            listener.Start(1);
            listener.BeginAcceptTcpClient(ClientConnected, listener);
        }
 //This method set the socket on listening mode...
 private void _set_listen()
 {
     //Let's do it asynchronously - Set the method callback, with the same definition as delegate _new_client
     _tcpListen.BeginAcceptTcpClient(new AsyncCallback(_on_new_client), null);
 }
        /// <summary>
        /// 侦听服务方法。
        /// </summary>
        /// <param name="ar"></param>
        private void ClientConnection(System.IAsyncResult ar)
        {
            //TcpListener listener = (TcpListener)ar.AsyncState;
            System.Net.Sockets.TcpListener listener = this.tcpListener;

            System.Net.Sockets.TcpClient client;
            try
            {
                client = listener.EndAcceptTcpClient(ar);
            }
            catch (System.ObjectDisposedException)
            {
                return;
            }
            catch (System.Exception)
            {
                return;
            }
            finally
            {
                if (!this.CallByStop)
                {
                    listener.BeginAcceptTcpClient(this.ClientConnection, null);
                }
            }

            TcpServerPoolEntity tcpServerPoolEntity = null;

            try
            {
                if (client.Connected)
                {
                    System.Net.Sockets.NetworkStream ns = client.GetStream();
                    try
                    {
                        //int linkMark = ns.ReadByte();
                        //if (linkMark != 1)
                        //{
                        //    return;
                        //}
                        //ns.WriteByte(1);
                        tcpServerPoolEntity = new TcpServerPoolEntity()
                        {
                            TcpClient = client, NetworkStream = ns
                        };
                        lock (this.TcpClientsLock)
                        {
                            this.TcpClients.Add(tcpServerPoolEntity);
                        }

                        if (this._TcpClientConnectionEvent != null)
                        {
                            this._TcpClientConnectionEvent(client, ns);
                        }
                    }
                    finally
                    {
                        ns.Flush();
                        ns.Close();
                    }
                }
            }
            finally
            {
                try
                {
                    client.Close();
                }
                finally
                {
                    if (tcpServerPoolEntity != null)
                    {
                        lock (this.TcpClientsLock)
                        {
                            this.TcpClients.Remove(tcpServerPoolEntity);
                        }
                    }
                }
            }
        }