示例#1
1
        /// <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);
            }
        }
示例#2
0
文件: Client.cs 项目: yangwenlong/ywl
    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());
        }
    }
示例#3
0
        // 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");

        }
示例#4
0
        private static void AcceptCallback(IAsyncResult ar)
        {
            allDone.Set (); // thread signal handler
            Socket listener	= (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept (ar);
            StateObject state = new StateObject ();
            state.WorkSocket = handler;

            Console.WriteLine ("CommunicationServer :: connection accepted ..");
            Send (handler, "Welcome to nafac.co IPC-Hub !! \n\r<EOF>");

            // IPC-Hub handshake
            /*
            byte[] bytes = new byte[1024];
            int bytesRec = handler.Receive(bytes);
            string ret   = Encoding.UTF8.GetString (bytes, 0, bytesRec);
            */
            // handshake
            // 	!!
            // AsyncRead
            handler.BeginReceive (state.buffer, 0, StateObject.buffersize, 0, new AsyncCallback (ReadCallback), state);

            //#Alpha6TODO ::
            //	0. get module type and hash.
            //	1. the highly secret handshake.
            //	2. pair hashed modules.
            //	3. bridge hashed modules.
        }
示例#5
0
        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);
                }
            }
        }
示例#6
0
        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();
                }
            }
        }
示例#7
0
        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());
            }
        }
示例#8
0
        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);
        }
示例#9
0
 public void Receive(StateObject state = null, AsyncCallback asyncCallBack = null)
 {
     if (state == null) { state = new StateObject(); }
     if (asyncCallBack == null) { asyncCallBack = new AsyncCallback(ReceiveCallback); }
     state.WorkSocket = socket;
     socket.BeginReceive(state.Buffer, 0, state.BufferSize, 0, asyncCallBack, state);
 }
 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;
 }
示例#11
0
文件: Socket.cs 项目: tjs12/DBProject
    public static void Receive0()
    {
        try
        {
            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = client;

            // Begin receiving the data from the remote device.
            //client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
            //    new AsyncCallback(ReceiveCallback), state);
            int bytesRead;
            response = "";
            while (true)
            {
                bytesRead = client.Receive(state.buffer);
                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
                Debug.WriteLine("Received: " + state.sb.ToString() + "\n");
                if (state.sb.ToString().Length >= 4 && state.sb.ToString().Substring(state.sb.ToString().Length - 4) == "#end")
                {
                    response = state.sb.ToString();
                    //form.setData(response);
                    return;
                }
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
示例#12
0
文件: Program.cs 项目: Sasha7b9/Osci
        static int Main(string[] args)
        {
            // Коннектимся
            byte[] addr = new byte[4];
            addr[0] = 192;
            addr[1] = 168;
            addr[2] = 1;
            addr[3] = 200;

            client.BeginConnect(new IPAddress(addr), port, new AsyncCallback(ConnectCallback), client);

            while(!client.Connected) { };

            StateObject state = new StateObject();
            state.workSocket = client;

            // Настраиваемся на приём
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);

            while(true)
            {
                string data = Console.ReadLine();
                if(data == "close")
                {
                    client.Close();
                    while(true) { };
                }
                Send(client, ":" + data + "\x0d\x0a");
            };

            return 0;
        }
示例#13
0
        private static void NewComingConnection(IAsyncResult result)
        {
            try
            {

                Socket s = result.AsyncState as Socket;
                StateObject state = new StateObject();
                int bytesTransferred = 0;
                byte[] data = null;
                Socket handler = s.EndAccept(out data, out bytesTransferred, result);
                //first 4 bytes data will be in data.  i don't know why bytesTransferrd is 56

                state.CommandType = (CommandType)BitConverter.ToInt32(data, 0);
                state.WorkSocket = handler;
                Console.WriteLine("New Connection commandType:" + state.CommandType);

                HandleCommandType(state);

            }
            catch (SocketException ex)
            {

            }
            finally
            {
                allDone.Set();
            }
        }
 public void Setup(StateObject s, SpellCard target, float delay)
 {
     this.s = s;
     this.target = target;
     this.delay = delay;
     invoked = true;
 }
示例#15
0
 /// <summary>
 ///  Thread for session with PythonServer
 /// </summary>
 private void Run()
 {
     try
     {
         // Build listener for python engine
         listener = new TcpListener(9669);
         listener.Start();
         //  Wait connection from python engine and if successful then create new socket to python engine
         pythonClient = listener.AcceptTcpClient();
         mainForm.PrintToLog(DateTime.Now.ToShortTimeString() + " :  Server trying start...", Color.Black);
         listener.Stop(); // stop listening because python engine connected to GUI
         flagRun = true;
         // Asynchronic StateObject
         StateObject stateObject = new StateObject();
         stateObject.workSocket = pythonClient.Client;
         // Begins to asynchronously receive data from a connected socket with  python engine
         pythonClient.Client.BeginReceive(stateObject.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(Read_Callback), stateObject);
     }
     catch (SocketException se)
     {
         mainForm.PrintToLog(se.Message, Color.Red);
     }
     catch (Exception e)
     {
         mainForm.PrintToLog(e.Message, Color.Red);
     }
 }
示例#16
0
 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();
     }
 }
示例#17
0
        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");
            };
        }
示例#18
0
        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());
            }
        }
示例#19
0
 private static void DecodeSample(StateObject state, int code, BinaryWriter writer)
 {
     int linearSample = CalculateSampleOverflowSafe(state, code);
     MoveToNextSampleClampedTo16Bit(state, linearSample);
     state.delta = (short)Math.Max((state.delta * AdaptationTable[code]) / 256, 16);
     writer.Write(state.sample1);
 }
示例#20
0
        public void CloseClient(object client)
        {
            Socket clientSoc = (Socket)client;
            string socId = "";

            try
            {
                socId = clientSoc.RemoteEndPoint.ToString();
                lock (mClientTableLock)
                {
                    mHtClientTable.Remove(clientSoc.RemoteEndPoint.ToString());
                }
            }
            catch (Exception e) { }

            StateObject stateObj = new StateObject(clientSoc);
            lock (mClientTableLock)
            {
                stateObj.key = mKey + "_Cli" + mHtClientTable.Count;
            }
            stateObj.status = SocHandlerStatus.DISCONNECTED;
            stateObj.socMessage = String.Format("{0} socket is removed from Socket list: ", socId);
            Logger.debug(stateObj);
            OnSocStatusChangedOnDebug(new SocStatusEventArgs(stateObj));

            try
            {
                clientSoc.Shutdown(SocketShutdown.Both);
                clientSoc.Close();
            }
            catch (Exception e)
            {
                setErrorMessage(e, string.Format("소켓접속해제:{0}", e.ToString()));
            }
        }
示例#21
0
        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);
            }

        }
        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();
                }
            }
        }
示例#23
0
        public void StartListening()
        {
            EndPoint localEp = ( EndPoint )_iep;
            Socket listener = new Socket( AddressFamily.InterNetwork,
                                          SocketType.Dgram,
                                          ProtocolType.Udp );
            try
            {
                listener.Bind( localEp );
                while ( true )
                {
                    allDone.Reset();
                    StateObject so = new StateObject();
                    so.workSocket = listener;
                    Console.WriteLine( "Waiting for a connection..." );
                    IAsyncResult result =
                    listener.BeginReceiveFrom( so.buffer,
                                              0,
                                              StateObject.BUFFER_SIZE,
                                              SocketFlags.None,
                                              ref localEp,
                                              new AsyncCallback( this.OnReceive ), so );
                    allDone.WaitOne();
                }

            }
            catch ( Exception e )
            {
                Console.WriteLine( e.ToString() );
            }
        }
 public void init()
 {
     try
     {
         Console.WriteLine("Init");
         //set up socket
         Socket client = new Socket(AddressFamily.InterNetwork,
         SocketType.Stream, ProtocolType.Tcp);
         //IPHostEntry hostInfo = Dns.Resolve("localhost:8000");
         //IPAddress address = hostInfo.AddressList[0];
         //IPAddress ipAddress = Dns.GetHostEntry("localhost:8000").AddressList[0];
         IPAddress ipAddress = new IPAddress(new byte[] { 128, 61, 105, 215 });
         IPEndPoint ep = new IPEndPoint(ipAddress, 8085);
         client.BeginConnect(ep, new AsyncCallback(ConnectCallback), client);
         connectDone.WaitOne();
         //receiveForever(client);
         byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
         StateObject state = new StateObject();
         state.workSocket = client;
         client.BeginReceive(buffer, 0, StateObject.BufferSize, 0,
                 new AsyncCallback(ReceiveCallback), state);
         client.Send(msg);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.ToString());
     }
 }
        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());
                }
            }
        }
示例#26
0
 public static void Send(Socket handler, String data, Boolean IsOver)
 {
     byte[] byteData = Encoding.UTF8.GetBytes(data);
     StateObject state = new StateObject();
     state.workSocket = handler;
     state.IsOver = IsOver;
     handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), state);
 }
示例#27
0
 /// <summary>
 /// Accepts the callback.
 /// </summary>
 /// <param name="syncResult">The synchronize result.</param>
 public static void AcceptCallback(IAsyncResult syncResult)
 {
     allDone.Set();
     Socket listener = (Socket)syncResult.AsyncState;
     handler = listener.EndAccept(syncResult);
     StateObject state = new StateObject();
     state.WorkSocket = handler;
 }
示例#28
0
 private static int CalculateSampleOverflowSafe(StateObject state, int code)
 {
     int adaptedSample1 = state.sample1 * AdaptCoeff1[state.predicator];
     int adaptedSample2 = state.sample2 * AdaptCoeff2[state.predicator];
     int linearSample = (adaptedSample1 + adaptedSample2) / 256;
     code = (code & 0x08) != 0 ? (code - 0x10) : code;
     return linearSample + (state.delta * code);
 }
 public override void SpellEffect(StateObject s)
 {
     foreach(Unit u in s.Units) {
         if(u != s.Caster.Base && u != s.Opponent.Base) {
             u.Damage(int.MaxValue);
         }
     }
 }
示例#30
0
 public void AddToState(GameObject g)
 {
     StateObject so = new StateObject(g);
     so.id = nextStateObjectId; 
     stateObjects.Add(so.id, so);
     nextStateObjectId++;
     CreateStateObjectButton(so);
 }
示例#31
0
 private static void MoveToNextSampleClampedTo16Bit(StateObject state, int linearSample)
 {
     state.sample2 = state.sample1;
     state.sample1 = (short)Math.Min(short.MaxValue, Math.Max(short.MinValue, linearSample));
 }
示例#32
0
文件: Listener.cs 项目: hzsydy/jiwang
        bool parseStateData(StateObject state)
        {
            Console.WriteLine("receive:" + common.ascii2Str(state.data));
            if (state.data.Count >= common.msg_position)
            {
                List <byte> msg_len_header = state.data.GetRange(common.msglen_position, common.msglen_length);
                int         msg_len        = Convert.ToInt32(common.ascii2Str(msg_len_header));

                int expect_len = common.msg_position + msg_len;

                if (state.data.Count >= expect_len)
                {
                    //all data received. parse it

                    List <byte> type_header = state.data.GetRange(0, common.type_header_length);
                    List <byte> name_header = state.data.GetRange(
                        common.type_header_length, common.name_header_length);
                    List <byte> msg = state.data.GetRange(common.msg_position, msg_len);

                    string type_str = common.ascii2Str(type_header);
                    string chatname = common.ascii2Str(name_header);

                    lock (thisLock)
                    {
                        if (type_str != common.type_str_quit_group)
                        {
                            ChatLink cl = register(chatname);
                            cl.onReceive(type_str, msg.ToArray());
                        }
                        else
                        {
                            if (reg_chatlinks.ContainsKey(chatname))
                            {
                                ChatLink cl = register(chatname);
                                cl.onReceive(type_str, msg.ToArray());
                            }
                        }
                    }


                    List <byte> left_msg = state.data.GetRange(expect_len,
                                                               state.data.Count - expect_len);
                    if (left_msg.Count == 0)
                    {
                        state.data = new List <byte>();
                    }
                    else
                    {
                        int notzero = left_msg.FindIndex((x) => x > 0);
                        if (notzero >= 0)
                        {
                            state.data = left_msg.GetRange(notzero, left_msg.Count - notzero);
                        }
                        else
                        {
                            state.data = new List <byte>();
                        }
                    }
                    state.buffer = new byte[common.buffersize];
                    return(true);
                }
            }
            return(false);
        }
        public void AcceptCallback(IAsyncResult _asyncResult)
        {
            //Get the socket that handles the client request.
            var _listenerSocket = (Socket)_asyncResult.AsyncState;

            if (_listenerSocket == null)
            {
                return;
            }

            //Get clientSocket
            try
            {
                decoderSocket = _listenerSocket.EndAccept(_asyncResult);

                //Shutdown listener only one client allowed
                listenerSocket.Close();
                listenerSocket = null;
            }
            catch (Exception ex)
            {
                Logger.WriteDebug($"{decoderName}: {ex} -> {ex.Message}");
            }

            //Check Connection
            if (decoderSocket == null || !decoderSocket.Connected)
            {
                Logger.WriteDebug($"{decoderName}: Disconnected");
                decoderStatus = ConnectionStatus.ClientDisconnected;

                //Raise event
                Disconnected.RaiseEvent(this, null);
                //Try to reconnect again;
                Restart();

                return;
            }


            //Start to receive
            try
            {
                Logger.WriteDebug($"{decoderName}: Connection from {decoderSocket.RemoteEndPoint}");
                decoderStatus = ConnectionStatus.ClientConnected;

                restartAttempts = 0;
                pingAttempts    = 0;

                //Send LoginString
                Send(loginString);

                // Begin receiving the data from the remote device.
                var _state = new StateObject();
                decoderSocket.BeginReceive(_state.Buffer, 0, StateObject.BufferSize, 0, ReceiveCallback, _state);

                //Raise event
                Connected.RaiseEvent(this, null);
            }
            catch (Exception ex)
            {
                Logger.WriteDebug($"{decoderName}: {ex} -> {ex.Message}");
            }
        }
示例#34
0
        static void ReadCallback(IAsyncResult ar)
        {
            StateObject state = (StateObject)ar.AsyncState;

            if (state.UseSSL)
            {
                if (!state.SslStream.CanRead)
                {
                    return;
                }
            }
            else
            {
                if (!state.RawIpSocket.Connected)
                {
                    return;
                }
            }

            byte[] readBytes;

            int bytesRead = 0;

            try
            {
                if (state.UseSSL)
                {
                    bytesRead = state.SslStream.EndRead(ar);
                }
                else
                {
                    bytesRead = state.RawIpSocket.EndReceive(ar);
                }
            }
            catch (Exception ex)
            {
                if (ex is SocketException)
                {
                    if (((SocketException)ex).ErrorCode == 10054)
                    {
                        bytesRead = -1;
                    }
                    state.Client.FireOnTerminatedEvent(((SocketException)ex).ErrorCode.ToString());
                }
                else
                {
                    state.Client.FireOnErrorEvent(TcpSocketExceptionType.ReceiveException, "EndReceive error: Code = " + ex.Message);
                    state.Client.FireOnTerminatedEvent(ex.Message);
                }
            }

            if (bytesRead > 0)
            {
                readBytes = new byte[bytesRead];
                System.Array.Copy(state.Buffer, readBytes, bytesRead);

                state.Client.FireOnDataWaitingEvent(readBytes);

                try
                {
                    if (state.UseSSL)
                    {
                        state.SslStream.BeginRead(state.Buffer, 0, state.BufferSize, new AsyncCallback(ReadCallback), state);
                    }
                    else
                    {
                        state.RawIpSocket.BeginReceive(state.Buffer, 0, state.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                    }
                }
                catch (Exception ex)
                {
                    state.Client.FireOnErrorEvent(TcpSocketExceptionType.ReceiveException, "BeginReceive error: Code = " + ex.Message);
                    state.Client.FireOnTerminatedEvent(ex.Message);
                }
            }
            else if (bytesRead == 0)
            {
                state.Client.FireOnTerminatedEvent("bytesRead = 0");
            }
        }
示例#35
0
        public void TestMethod1()
        {
            StateObject st = new StateObject();

            Assert.IsNotNull(st);
        }
        private void ProcessSocketCommand()
        {
            Thread.CurrentThread.IsBackground = true; //后台线程
            while (true)
            {
                try
                {
                    if (!SEQueue.IsEmpty)
                    {
                        SocketEntity seEntity = null;
                        bool         isHas    = SEQueue.TryDequeue(out seEntity);
                        if (isHas)
                        {
                            string      returnValue = "";
                            string      strSN       = seEntity.dCommand;
                            string      ipAndPort   = seEntity.dIPAddress;
                            Socket      handler     = seEntity.dSocket;
                            StateObject state       = seEntity.dState;
                            string[]    values      = strSN.Split(new char[] { ';' });
                            IPEndPoint  remotepoint = null;
                            try
                            {
                                remotepoint = (IPEndPoint)handler.RemoteEndPoint;
                            }
                            catch (Exception)
                            {
                                continue;
                            }

                            if (strSN.StartsWith("01;"))
                            {
                                string workorder = values[1];
                                //get sn
                                string serialNumber = "";// mv.GenerateSerialNumber(workorder);
                                returnValue = "#01;" + serialNumber;
                            }
                            else if (strSN.StartsWith("03;"))//stock in
                            {
                                string mtoNo   = values[1];
                                string plantNo = values[2];
                                //returnValue = "#03;" + mv.ProcessMTOData(mtoNo, plantNo, "STOCK_IN");
                            }
                            else if (strSN.StartsWith("04;"))
                            {
                                string mtoNo  = values[1];
                                string partNo = values[2];
                                string status = values[3];
                                //string strValue = mv.ProcessStockIN04(mtoNo, partNo, status);
                                //returnValue = "#04;" + strValue;
                            }
                            else if (strSN.StartsWith("05;"))
                            {
                                string  mtoNo      = values[1];
                                string  partNo     = values[2];
                                string  location   = values[3];
                                string  status     = values[4];
                                decimal qtyStocked = Convert.ToDecimal(values[5]);
                                decimal qtyRest    = Convert.ToDecimal(values[6]);
                                //string strValue = mv.ProcessStockIN05(mtoNo, partNo, location, status, qtyStocked, qtyRest);
                                //returnValue = "#05;" + strValue;
                            }
                            else if (strSN.StartsWith("06;"))//stock out
                            {
                                string mtoNo   = values[1];
                                string plantNo = values[2];
                                //returnValue = "#06;" + mv.ProcessMTOData(mtoNo, plantNo, "STOCK_OUT");
                            }
                            else if (strSN.StartsWith("07;"))//stock out---Update “CUST. MATERIAL_TRANSFER_ORDER”,  For each part number in MTO Material List,
                            {
                                string  mtoNo      = values[1];
                                string  plantNo    = values[2];
                                string  partNumber = values[3];
                                decimal dQty       = Convert.ToDecimal(values[4]);
                                //returnValue = "#07;" + mv.ProcessStockOut07(mtoNo, plantNo, partNumber, dQty);
                            }
                            else if (strSN.StartsWith("00"))
                            {
                                try
                                {
                                    returnValue = "#00;OK#";
                                    byte[] byteData1 = Encoding.GetEncoding("UTF-8").GetBytes(returnValue);//回发信息
                                    handler.BeginSend(byteData1, 0, byteData1.Length, 0, new AsyncCallback(SendCallback), handler);
                                    //mv.SetConsoleText("Send message to (Client)IP:" + remotepoint.Address + " Port:" + remotepoint.Port + " -----" + returnValue + System.Environment.NewLine);
                                }
                                catch (Exception ex)
                                {
                                    LogHelper.Error(ex);
                                }
                                //mv.SetCurrentConnectText("IP-" + remotepoint.Address + " Port-" + remotepoint.Port + " stop connect");
                                try
                                {
                                    handler.Shutdown(SocketShutdown.Both);
                                    handler.Disconnect(true);
                                    handler.Close();
                                    LogHelper.Info("Remove IP-" + remotepoint.Address + " Port-" + remotepoint.Port);
                                }
                                catch (Exception ex)
                                {
                                    LogHelper.Error(ex);
                                }
                            }
                            else
                            {
                                returnValue = "-----Formate error";// +valueTSA;
                            }

                            if (!strSN.StartsWith("00"))
                            {
                                returnValue = returnValue + "#";                                       //System.Environment.NewLine;
                                byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(returnValue); //回发信息
                                try
                                {
                                    handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
                                    //mv.SetConsoleText("Send message to (Client)IP:" + remotepoint.Address + " Port:" + remotepoint.Port + " -----" + returnValue + System.Environment.NewLine);
                                }
                                catch (Exception ex)
                                {
                                    LogHelper.Error(ex);
                                }
                            }
                        }
                    }
                    Thread.Sleep(1000);
                }

                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                }
            }
        }
        public void ReadCallback(IAsyncResult ar)
        {
            StateObject state   = (StateObject)ar.AsyncState;
            Socket      handler = state.workSocket;

            if (!handler.Connected)
            {
                return;
            }
            state.dTime = DateTime.Now;
            IPEndPoint remotepoint = null;

            try
            {
                remotepoint = (IPEndPoint)handler.RemoteEndPoint;
            }
            catch (Exception ex)
            {
                clientList.Remove(state);
                LogHelper.Error(ex);
                return;
            }
            // Read data from the client socket.
            int bytesRead = 0;

            try
            {
                bytesRead = handler.EndReceive(ar);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex.StackTrace);
                return;
            }
            if (bytesRead > 0)
            {
                string contentstr = ""; //接收到的数据
                contentstr = Encoding.GetEncoding("UTF-8").GetString(state.buffer, 0, bytesRead);
                LogHelper.Info("message:" + contentstr);

                string       strSN     = contentstr.Replace("#", "");
                string       ipAndPort = remotepoint.Address.ToString(); //+ ";" + remotepoint.Port.ToString();
                SocketEntity entity    = new SocketEntity();
                entity.dCommand   = strSN;
                entity.dState     = state;
                entity.dIPAddress = ipAndPort;
                entity.dSocket    = handler;
                SEQueue.Enqueue(entity);
                //mv.SetConsoleText("Receive message from (client)IP:" + remotepoint.Address + " Port:" + remotepoint.Port + " -----" + strSN);

                try
                {
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex.Message + ";" + ex.StackTrace);
                }
            }
            else
            {
                //mv.SetConsoleText("IP-" + remotepoint.Address + " Port-" + remotepoint.Port + " stop connect");
                try
                {
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Disconnect(true);
                    handler.Close();
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                }
            }
        }
示例#38
0
    public static void ReadCallback(IAsyncResult ar)
    {
        String content = String.Empty;

        // Retrieve the state object and the handler socket
        // from the asynchronous state object.
        StateObject state   = (StateObject)ar.AsyncState;
        Socket      handler = state.workSocket;

        // Read data from the client socket.
        int bytesRead;

        try
        {
            bytesRead = handler.EndReceive(ar);
        }
        catch
        {
            Brodcaster.RemoveSocket(handler);
            return;
        }

        if (bytesRead > 0)
        {
            for (int i = bytesRead; i < state.buffer.Length; i++)
            {
                state.buffer[i] = 0;
            }
            // There  might be more data, so store the data received so far.
            //state.sb.Append(Encoding.ASCII.GetString(
            //   state.buffer, 0, bytesRead));

            // Check for end-of-file tag. If it is not there, read
            // more data.
            // content = state.sb.ToString();


            //Brodcaster.NotifyAllExept(handler, state.buffer);
            string income = Encoding.ASCII.GetString(state.buffer, 0, bytesRead);
            if (income.Contains('\n'))
            {
                Brodcaster.NotifyAllExept(handler, Encoding.ASCII.GetBytes("\r\n"));
            }
            ProcessCMD.Write(income);
            if (!income.Contains('\n'))
            {
                Brodcaster.SendToAll(Encoding.ASCII.GetBytes('\r' + ProcessCMD.GetCurrentDirectory() + ProcessCMD.GetCommand()));
            }


            if (income.IndexOf('\n') > -1)
            {
                //Brodcaster.NotifyAllExept(null, Encoding.ASCII.GetBytes(ProcessCMD.GetCurrentDirectory()));
            }


            // Not all data received. Get more.
            try
            {
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                     new AsyncCallback(ReadCallback), state);
            }
            catch
            {
                Brodcaster.RemoveSocket(handler);
            }
        }
        else
        {
            Brodcaster.RemoveSocket(handler);
            handler.Shutdown(SocketShutdown.Both);
            handler.Close();
        }
    }
示例#39
0
        private void ConnectToHostAndSendRequestCallback <T>(IAsyncResult asynchronousResult)
        {
            StateObject <T>  asynchStateObject  = asynchronousResult.AsyncState as StateObject <T>;
            RequestState <T> asynchRequestState = asynchStateObject.RequestState;

            string channels = "";

            if (asynchRequestState != null && asynchRequestState.Channels != null)
            {
                channels = string.Join(",", asynchRequestState.Channels);
            }

            try
            {
                string    requestString = asynchStateObject.requestString;
                TcpClient tcpClient     = asynchStateObject.tcpClient;

                NetworkStream netStream = asynchStateObject.netStream;
                int           bytesRead = netStream.EndRead(asynchronousResult);

                if (bytesRead > 0)
                {
                    asynchStateObject.sb.Append(Encoding.ASCII.GetString(asynchStateObject.buffer, 0, bytesRead));

                    netStream.BeginRead(asynchStateObject.buffer, 0, StateObject <T> .BufferSize,
                                        new AsyncCallback(ConnectToHostAndSendRequestCallback <T>), asynchStateObject);
                }
                else
                {
                    string resp = asynchStateObject.sb.ToString();
                    if (resp.IndexOf("200 Connection established") > 0)
                    {
                        SendSslRequest <T>(netStream, tcpClient, asynchRequestState, requestString);
                    }
                    else
                    {
                        throw new WebException("Couldn't connect to the server");
                    }
                }
            }
            catch (WebException webEx)
            {
                if (asynchRequestState != null && asynchRequestState.ErrorCallback != null)
                {
                    Action <PubnubClientError> errorCallback = asynchRequestState.ErrorCallback;

                    CallErrorCallback(PubnubErrorSeverity.Warn, PubnubMessageSource.Client,
                                      channels, errorCallback, webEx, null, null);
                }
                ProcessResponseCallbackWebExceptionHandler <T>(webEx, asynchRequestState, channels);
            }
            catch (Exception ex)
            {
                if (asynchRequestState != null && asynchRequestState.ErrorCallback != null)
                {
                    Action <PubnubClientError> errorCallback = asynchRequestState.ErrorCallback;
                    CallErrorCallback(PubnubErrorSeverity.Warn, PubnubMessageSource.Client,
                                      channels, errorCallback, ex, null, null);
                }
                ProcessResponseCallbackExceptionHandler <T>(ex, asynchRequestState);
            }
        }
示例#40
0
        private void Send(StateObject client, byte[] msg, int bufferLength)
        {
            while (transmittingData)
            {
            }
            transmittingData = true;

            // first, send the number of bytes it will transfer in the next send
            client.ExpectedSendBytes = 4;
#if USE_VARIABLE_BUFFER_SIZE
            client.SendSocket.SendBufferSize = 4;
#endif
            sendEvent.Reset();
            try
            {
#if DEBUG_NETWORK
                Log.Write("Sending length: " + msg.Length);
#endif
                client.SendSocket.BeginSend(BitConverter.GetBytes(msg.Length), 0, 4, 0,
                                            new AsyncCallback(SendCallback), client);
            }
            catch (SocketException exp)
            {
                DisconnectClient(client, true);
                sendEvent.Set();
                return;
            }
            sendEvent.WaitOne(100);

            if (bufferLength > sendBufferSize)
            {
                sendBufferSize = bufferLength;
                client.SendSocket.SendBufferSize = sendBufferSize;
            }

#if USE_VARIABLE_BUFFER_SIZE
            client.SendSocket.SendBufferSize = sendBufferSize;
#endif
            // now we are ready to send the actual data
            client.ExpectedSendBytes = msg.Length;

            try
            {
#if DEBUG_NETWORK
                string debugData = "Sending actual data: ";
                foreach (byte b in msg)
                {
                    debugData += b + " ";
                }
                Log.Write(debugData);
#endif
                client.SendSocket.BeginSend(msg, 0, msg.Length, 0,
                                            new AsyncCallback(SendCallback), client);
            }
            catch (SocketException exp)
            {
                DisconnectClient(client, true);
                sendEvent.Set();
                return;
            }
        }
示例#41
0
        private void ReadCallback(IAsyncResult ar)
        {
            StateObject state   = (StateObject)ar.AsyncState;
            Socket      handler = state.ReceiveSocket;

            int bytesRead = 0;

            try
            {
                bytesRead = handler.EndReceive(ar);
            }
            catch (Exception) { return; }

            /*if (bytesRead != state.ExpectedReceiveBytes)
             *  Log.Write("Did not receive all expected bytes. Expected: " + state.ExpectedReceiveBytes +
             *      ", Received: " + bytesRead);*/

            if (bytesRead == 4)
            {
                state.ExpectedReceiveBytes = BitConverter.ToInt32(state.PreReceiveBuffer, 0);
                int bufferSize = ByteHelper.RoundToPowerOfTwo(state.ExpectedReceiveBytes);

                if (bufferSize > recvBufferSize)
                {
                    bool change = false;
                    if (bufferSize > MAX_BUFFER_SIZE)
                    {
                        if (recvBufferSize != MAX_BUFFER_SIZE)
                        {
                            recvBufferSize = MAX_BUFFER_SIZE;
                            change         = true;
                        }
                    }
                    else
                    {
                        recvBufferSize = bufferSize;
                        change         = true;
                    }

                    if (change)
                    {
                        state.ReceiveSocket.ReceiveBufferSize = recvBufferSize;
                        state.ReceiveBuffer = new byte[recvBufferSize];
                    }
                }

#if USE_VARIABLE_BUFFER_SIZE
                state.ReceiveSocket.ReceiveBufferSize = recvBufferSize;
#endif
                int receivingBytes = (state.ExpectedReceiveBytes > recvBufferSize) ? recvBufferSize :
                                     state.ExpectedReceiveBytes;
                try
                {
                    handler.BeginReceive(state.ReceiveBuffer, 0, receivingBytes, 0,
                                         new AsyncCallback(ReadCallback), state);
                }
                catch (Exception exp) { }
            }
            else
            {
                if (bytesRead == 10)
                {
                    string msg = Encoding.UTF8.GetString(state.ReceiveBuffer, 0, bytesRead);
                    if (msg.Equals("@Shutdown@"))
                    {
                        DisconnectClient(state, false);

                        return;
                    }
                }

                // busy wait until the ReceiveMessage call finishes
                while (copyingRecvBuffer)
                {
                }
                receivingData = true;

                int newOffset = state.Offset + bytesRead;
                if (newOffset > state.ReceivedData.Length)
                {
                    byte[] tmp = new byte[state.Offset];
                    Buffer.BlockCopy(state.ReceivedData, 0, tmp, 0, state.Offset);
                    int newLength = ByteHelper.RoundToPowerOfTwo(newOffset);
                    state.ReceivedData = new byte[newLength];
                    Buffer.BlockCopy(tmp, 0, state.ReceivedData, 0, state.Offset);
                }
                Buffer.BlockCopy(state.ReceiveBuffer, 0, state.ReceivedData, state.Offset, bytesRead);
                state.Offset += bytesRead;

                if (!recentlyReceivedStates.Contains(state) && state.Offset >= state.ExpectedReceiveBytes)
                {
                    recentlyReceivedStates.Add(state);
                }
                receivingData = false;

                if (state.Offset >= state.ExpectedReceiveBytes)
                {
#if USE_VARIABLE_BUFFER_SIZE
                    state.ReceiveSocket.ReceiveBufferSize = 4;
#endif
                    state.ExpectedReceiveBytes = 4;
                    try
                    {
                        handler.BeginReceive(state.PreReceiveBuffer, 0, state.PreReceiveBuffer.Length, 0,
                                             new AsyncCallback(ReadCallback), state);
                    }
                    catch (Exception exp) { }
                }
                else
                {
                    int receivingBytes = state.ExpectedReceiveBytes - state.Offset;
                    if (receivingBytes > recvBufferSize)
                    {
                        receivingBytes = recvBufferSize;
                    }
                    try
                    {
                        handler.BeginReceive(state.ReceiveBuffer, 0, receivingBytes, 0,
                                             new AsyncCallback(ReadCallback), state);
                    }
                    catch (Exception exp) { }
                }
            }
        }
示例#42
0
        private void ReceivedOrder(IAsyncResult ar)
        {
            isSendColor     = false;
            isSendBodyIndex = false;
            StateObject so = (StateObject)ar.AsyncState;

            DataReceive       listCommand;
            KinectDataRequest request;

            try
            {
                int read = so.socket.EndReceive(ar);
                lock (this)
                {
                    so.socket.BeginReceive(so.buffer, 0, so.buffer.Length, 0, new AsyncCallback(ReceivedOrder), so);
                }

                if (read == 0)
                {
                    so.socket.Shutdown(SocketShutdown.Both);
                }
                else
                {
                    //Console.WriteLine(so.socket.RemoteEndPoint.AddressFamily + " sending data " + read);
                    lock (this)
                    {
                        so.sb.Clear();
                        so.sb.Append(Encoding.UTF8.GetString(so.buffer, 0, read));
                        string jsonCommand = so.sb.ToString();
                        //Console.WriteLine(jsonCommand);

                        //String fakeJSON = "{\"command\":\"requestData\",\"dataReceive\":{\"colorImage\":true,\"bodyIndexImage\":false,\"bodyData\":true}}";

                        request     = JsonConvert.DeserializeObject <KinectDataRequest>(jsonCommand);
                        listCommand = request.dataReceive;

                        //StringBuilder newsb = so.sb;


                        isSendColor     = listCommand.colorImage;
                        isSendBodyIndex = listCommand.bodyIndexImage;
                        isSendBodyData  = listCommand.bodyData;
                    }
                    Console.WriteLine("======> request received");
                    //Console.WriteLine("isSendColor:" + isSendColor + ", isSendBodyIndex:" + isSendBodyIndex + ", isSendBodyData:" + isSendBodyData);

                    so.sb.Clear();
                }
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.ToString() + "\n Error Code:" + se.ErrorCode);
                IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7001);

                so.socket = new Socket(ipEnd.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                so.socket.Bind(ipEnd);
                so.socket.Listen(1);

                so.socket.BeginAccept(new AsyncCallback(AcceptCallback), so);
                sock = so.socket;
            }
            catch (ObjectDisposedException ode)
            {
                Console.WriteLine(ode.StackTrace);
            }
        }
示例#43
0
    public string ParseCommand(string command, StateObject st)
    {
        object ob = ParseCommandInner(command, st);

        return(JsonConvert.SerializeObject(ob));
    }
示例#44
0
 public void ReloadState(StateObject state)
 {
     _createdAtUtc = state.CreatedTimeUtc;
 }
 protected void OnEstablished(StateObject a_oStateObj)
 {
     a_oStateObj.GetData <ClientService>().AsyncReceive();
 }
示例#46
0
 // Handler to actually perform the command
 public abstract void Handle(StateObject state);
示例#47
0
        /// <summary>
        /// 消息处理
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static void process(StateObject request)
        {
//            <?xml version="1.0" encoding="utf-8"?>
//<ROOT>
//    <ITEM>
//<ID></ID>
//<DEVID>1</ DEVID >
//<DEVNAME></ DEVNAME >
//<DEVTYPE></ DEVTYPE >
//<IP></ IP >
//<PORT></ PORT >
//<UPDEVID></ UPDEVID >
//<DESCR></ DESCR >
//    </ITEM>
//</ROOT>

            //哈希表存放包体内容
            Hashtable _hashtable_Package = new Hashtable();
            string    DevID     = ""; //设备编号
            string    DevName   = ""; //设备名称
            int       DevTypeID = 0;  //设备类型编号
            string    IP        = ""; //IP地址
            string    PORT      = ""; //端口号
            string    UPDEVID   = ""; //上级设备编号
            string    DESCR     = ""; //说明
            int       intID     = 0;  //设备信息索引编号

            try
            {
                if (request != null)
                {
                    #region 包体解析
                    short cmd1 = 0; //主命令字
                    short cmd2 = 0; //子命令字
                    cmd1 = OMSCmd.DevInfoModify;
                    cmd2 = ErrCommon.Success;
                    byte[]    ByteResult = null;
                    DataTable dt         = new DataTable();
                    Commonality.CommClass.ReadXML(request.receiveFileTemporarily, ref dt);

                    if (dt.Rows.Count <= 0)
                    {
                        cmd2 = -101;//解包失败
                        //哈希表存放包体内容
                        Hashtable _hashtable_Package_Temp = new Hashtable();
                        _hashtable_Package_Temp.Add("1", request);//...連結位置
                        _hashtable_Package_Temp.Add("2", cmd1);
                        _hashtable_Package_Temp.Add("3", cmd2);
                        ByteResult = null;
                        _hashtable_Package_Temp.Add("4", ByteResult);
                        ThreadPool.QueueUserWorkItem(new WaitCallback(CommonFunction.SendDatas), _hashtable_Package_Temp);
                        Commonality.ConsoleManage.Write(Commonality.ErrorLevel.Serious,
                                                        "KOIPMonitor>>DevInfoModify>>process>>", "消息体内容有误");
                        return;
                    }

                    try
                    {
                        intID = Convert.ToInt32(dt.Rows[0]["ID"].ToString());
                    }
                    catch
                    {
                        intID = 0;
                    }

                    DevID   = dt.Rows[0]["DEVID"].ToString();
                    DevName = dt.Rows[0]["DEVNAME"].ToString();
                    try
                    {
                        DevTypeID = Convert.ToInt32(dt.Rows[0]["DEVTYPE"].ToString());
                    }
                    catch
                    {
                        DevTypeID = 0;
                    }
                    IP      = dt.Rows[0]["IP"].ToString();
                    PORT    = dt.Rows[0]["PORT"].ToString();
                    UPDEVID = dt.Rows[0]["UPDEVID"].ToString();
                    DESCR   = dt.Rows[0]["DESCR"].ToString();


                    int Ret = -1;

                    DevInfo_Modify(intID, DevID,
                                   DevName,
                                   DevTypeID,
                                   IP,
                                   PORT,
                                   UPDEVID,
                                   DESCR, ref Ret);
                    switch (Ret)
                    {
                    case -1:
                        cmd2 = -8018;
                        break;

                    case 0:
                        cmd2       = ErrCommon.Success;
                        ByteResult = BitConverter.GetBytes(intID);
                        CommonFunction.GetServerList();
                        break;
                    }


                    #endregion

                    Hashtable _hashtable_PackageArry = new Hashtable();
                    _hashtable_PackageArry.Add("1", request);//...連結位置
                    _hashtable_PackageArry.Add("2", cmd1);
                    _hashtable_PackageArry.Add("3", cmd2);
                    _hashtable_PackageArry.Add("4", ByteResult);
                    ThreadPool.QueueUserWorkItem(new WaitCallback(CommonFunction.SendDatas), _hashtable_PackageArry);
                    //CommonFunction.NoticeServerList();
                }
                else
                {
                    Commonality.ConsoleManage.Write(Commonality.ErrorLevel.Serious, "KOIPMonitor>>DevInfoModify>>process>>", "StateObject request==null");
                }
            }
            catch (Exception ex)
            {
                Commonality.ConsoleManage.Write(Commonality.ErrorLevel.Serious, "KOIPMonitor>>DevInfoModify>>process>>", ex.Message);
            }
            finally
            {
                //删除文件
                //if (!string.IsNullOrEmpty(request.receiveFileTemporarily))
                //    ThreadPool.QueueUserWorkItem(new WaitCallback(DiskIO.Del), request.receiveFileTemporarily);

                //GC.Collect();
            }
        }
示例#48
0
 // Regex to search to find if this service can handle the incoming command
 public abstract bool CanHandle(StateObject state);
示例#49
0
        public IMessage ProcessResponse(StateObject Object = null)
        {
            Console.WriteLine(this);

            return(this);
        }
 public TaskWithDeadlock(StateObject s1, StateObject s2) => (_s1, _s2) = (s1, s2);
示例#51
0
        bool Connect()
        {
            // Resolve listening end point.
            IPEndPoint remoteEP;

            try
            {
                IPAddress address = null;
                if (!IPAddress.TryParse(HostName, out address))
                {
                    foreach (IPAddress addr in Dns.GetHostEntry(HostName).AddressList)
                    {
                        if (addr.AddressFamily == AddressFamily.InterNetwork)
                        {
                            address = addr;
                        }
                    }
                }
                remoteEP = new IPEndPoint(address, HostPort);
            }
            catch
            {
                throw (new TcpSocketException(TcpSocketExceptionType.ConnectException, "DNS resolution failed: " + HostName));
            }

            // Being connect sequence.
            rawIpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            if (UseKeepAlive)
            {
                try
                {
                    rawIpSocket.SetKeepAlive(true, 60000UL /*60 seconds*/, 1000UL /*1 second*/);
                }
                catch (Exception e)
                {
                    FireOnErrorEvent(TcpSocketExceptionType.SendException, String.Format("Error setting socket options. {0}{1}{2}", e.Message, Environment.NewLine, e.StackTrace));
                }
            }

            StateObject state = new StateObject(rawIpSocket, this, UseSSL);

            try
            {
                rawIpSocket.BeginConnect(remoteEP.Address, remoteEP.Port, new AsyncCallback(ConnectCallback), state);
            }
            catch (Exception ex)
            {
                throw (new TcpSocketException(TcpSocketExceptionType.ConnectException, "BeginConnect error: Code = " + ex.Message));
            }

            if (!connectEvent.WaitOne(5000, false))
            {
                Thread.Sleep(100);
                throw (new TcpSocketException(TcpSocketExceptionType.ConnectException, "Socket connect failed - timeout."));
            }

            Thread.Sleep(100);

            if (UseSSL)
            {
                sslStream = state.SslStream;
                if (sslStream == null || !(sslStream.CanRead && sslStream.CanWrite))
                {
                    return(false);
                }
                //throw ( new IPClientException( IPClientExceptionType.ConnectException, "SSL connect failed." ) );
            }
            else
            {
                if (rawIpSocket == null || !rawIpSocket.Connected)
                {
                    return(false);
                }
                //throw ( new IPClientException( IPClientExceptionType.ConnectException, "Socket connect failed." ) );
            }

            return(true);
        }
示例#52
0
    public void ReadCallback(IAsyncResult ar)
    {
        String content = String.Empty;

        // Retrieve the state object and the handler socket
        // from the asynchronous state object.
        StateObject state   = (StateObject)ar.AsyncState;
        Socket      handler = state.workSocket;

        // Read data from the client socket.
        int bytesRead = 0;

        try
        {
            bytesRead = handler.EndReceive(ar);
        }
        catch (SocketException ex)
        {
            Console.WriteLine("forced disconnect");
            handler.Shutdown(SocketShutdown.Both);
            handler.Close();
            return;
        }

        if (bytesRead > 0)
        {
            // There  might be more data, so store the data received so far.
            //state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
            state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));

            // Check for end-of-file tag. If it is not there, read more data.
            content = state.sb.ToString();
            if (content.IndexOf("\r\n") > -1)
            {
                int x   = content.IndexOf("\r\n");
                int len = int.Parse(content.Substring(0, x));
                //Console.WriteLine("size = "+len.ToString());
                string cmd = content.Substring(x + 2);
                if (cmd.Length == len)
                {
                    // All the data has been read from the client
                    //Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", cmd.Length, cmd );

                    string result = ParseCommand(cmd, state);
                    state.sb = new StringBuilder();

                    // Echo the data back to the client.
                    Send(handler, result);

                    // check if client asked disconnection
                    if (state.disconnect)
                    {
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        return;
                    }
                }
            }
        }

        // Not all data received. Get more.
        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
    }
示例#53
0
        void ReceiveCallback(IAsyncResult ar)
        {
            StateObject state    = ar.AsyncState as StateObject;
            bool        disposed = false; //是否停止数据接收
            int         length   = 0;     //接收到的数据长度

            try
            {
                //接收 对应 客户端发来的消息
                length = ((Socket)state.State).EndReceive(ar);
                byte[] receiveBytes = new byte[length];
                Array.Copy(state.Buffer, 0, receiveBytes, 0, length);

                dataTime = DateTimeHelper.Now; //更新收到数据时间

                int    head    = -1;           //消息头码
                string strData = null;         //String类型消息
                if (length >= 4)
                {
                    //消息头码
                    head = BitConverter.ToInt32(new[] { receiveBytes[0], receiveBytes[1], receiveBytes[2], receiveBytes[3] }, 0);

                    if (head == 8888) //握手头码
                    {
                        trustedClient = true;
                        SendHandShake();
                        if (ShowAllData && DisplayMsg != null)
                        {
                            DisplayMsg(this, "收到握手包,客户端确认", DateTimeHelper.Now);
                        }
                    }
                    else if (head == 7777) //心跳信息
                    {
                        if (trustedClient)
                        {
                            connTime = DateTimeHelper.Now;
                        }
                        strData = ParserString(receiveBytes);
                        string[] infos = strData.Split(';');
                        ClientVer = infos[0];
                        DocID     = string.IsNullOrWhiteSpace(infos[1]) ? "未登录" : infos[1];
                        DocName   = infos[2];
                        if (ShowAllData && DisplayMsg != null)
                        {
                            DisplayMsg(this, "收到心跳包:" + strData, DateTimeHelper.Now);
                        }
                        InvokePropertyChanged("Name");
                    }
                    else if (head == 9999) //请求断开连接
                    {
                        CloseConnection("客户端退出");
                    }
                    else if (head == 0 && trustedClient) //发送来的是消息
                    {
                        strData = ParserString(receiveBytes);
                        if (DisplayMsg != null)
                        {
                            DisplayMsg(this, "收到文字消息:" + strData, DateTimeHelper.Now);
                        }
                    }
                    else
                    {
                        if (ShowAllData && DisplayMsg != null)
                        {
                            DisplayMsg(this, "收到未知消息", DateTimeHelper.Now);
                        }
                    }
                }
                if (DataReceived != null)
                {
                    try
                    {
                        DataReceived(this, head, receiveBytes, strData);
                    }
                    catch { }
                }
            }
            catch (Exception ex)
            {
                if (ex is ObjectDisposedException)
                {
                    disposed = true;
                    return; //停止接收数据
                }
                if (ex is SocketException)
                {
                    CloseConnection("客户端掉线");
                    return;
                }
                LogHelper.WriteError(ex, "TCP");
                if (DisplayMsg != null)
                {
                    DisplayMsg(this, "客户端消息处理失败", DateTimeHelper.Now);
                }
            }
            finally
            {
                try
                {
                    if (!disposed && length != 0)
                    {
                        //继续接收消息
                        ((Socket)state.State).BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ReceiveCallback, state);
                    }
                    if (length == 0)
                    {
                        CloseConnection("客户端关闭连接", false);
                    }
                }
                catch
                {
                    CloseConnection("接收消息异常");
                }
            }
        }
示例#54
0
    public object ParseCommandInner(string command, StateObject st)
    {
        Command cmd;

        try
        {
            cmd = JsonConvert.DeserializeObject <Command>(command);
        }
        catch (Exception ex)
        {
            return(new ErrorResult("invalid command"));
        }

        if (cmd.type == "open")
        {
            if (st.database.Connected)
            {
                return(new ErrorResult("already connected"));
            }

            try
            {
                st.database.connectionString = cmd.text;
                st.database.Open();
                return(new OkResult());
            }
            catch (Exception ex)
            {
                return(new ErrorResult(ex.Message));
            }
        }
        else if (cmd.type == "close")
        {
            if (!st.database.Connected)
            {
                return(new ErrorResult("not connected"));
            }

            st.database.Close();
            st.disconnect = true;
            return(new OkResult());
        }
        else if (cmd.type == "table")
        {
            if (!st.database.Connected)
            {
                return(new ErrorResult("not connected"));
            }

            try
            {
                var table = st.database.QueryTable(cmd.text);
                return(new TableResult(table));
            }
            catch (Exception ex)
            {
                return(new ErrorResult(ex.Message));
            }
        }
        else if (cmd.type == "postback")
        {
            if (!st.database.Connected)
            {
                return(new ErrorResult("not connected"));
            }

            ChangeSet changes;
            try
            {
                changes = JsonConvert.DeserializeObject <ChangeSet>(cmd.text);
            }
            catch (Exception ex)
            {
                return(new ErrorResult("invalid postback command"));
            }

            try
            {
                var response = PostBackManager.DoPostBack(st.database, changes);
                return(new PostBackResult(response.idcolumn, response.identities));
            }
            catch (Exception ex)
            {
                return(new ErrorResult(ex.Message));
            }
        }
        else if (cmd.type == "query")
        {
            if (!st.database.Connected)
            {
                return(new ErrorResult("not connected"));
            }

            try
            {
                var query = st.database.Query(cmd.text);
                return(new DataResult(query));
            }
            catch (Exception ex)
            {
                return(new ErrorResult(ex.Message));
            }
        }
        else if (cmd.type == "querysingle")
        {
            if (!st.database.Connected)
            {
                return(new ErrorResult("not connected"));
            }

            try
            {
                var query = st.database.QuerySingle(cmd.text);
                return(new DataResult(query));
            }
            catch (Exception ex)
            {
                return(new ErrorResult(ex.Message));
            }
        }
        else if (cmd.type == "queryvalue")
        {
            if (!st.database.Connected)
            {
                return(new ErrorResult("not connected"));
            }

            try
            {
                var query = st.database.QueryValue(cmd.text);
                return(new DataResult(query));
            }
            catch (Exception ex)
            {
                return(new ErrorResult(ex.Message));
            }
        }
        else if (cmd.type == "execute")
        {
            if (!st.database.Connected)
            {
                return(new ErrorResult("not connected"));
            }

            try
            {
                var query = st.database.Execute(cmd.text);
                return(new DataResult(query));
            }
            catch (Exception ex)
            {
                return(new ErrorResult(ex.Message));
            }
        }
        else
        {
            return(new ErrorResult("unknown command"));
        }
    }
    public static void ReadCallback(IAsyncResult ar)
    {
        String content = String.Empty;

        //IniFileHelper
        IniFileHelper iniFile = new IniFileHelper();

        // Retrieve the state object and the handler socket
        // from the asynchronous state object.
        StateObject state   = (StateObject)ar.AsyncState;
        Socket      handler = state.workSocket;

        // Read data from the client socket.
        int bytesRead = handler.EndReceive(ar);

        if (bytesRead > 0)
        {
            // There  might be more data, so store the data received so far.
            state.sb.Append(Encoding.ASCII.GetString(
                                state.buffer, 0, bytesRead));

            // Check for end-of-file tag. If it is not there, read
            // more data.
            content = state.sb.ToString();
            if (content.IndexOf("\r") > -1)
            {
                string ReceivedOutput = null;

                switch (content.Substring(0, 3))
                {
                case "611":
                    string device1Result = iniFile.ReadValue("Device1", "status", System.IO.Path.GetFullPath("IniFile.ini"));
                    string device2Result = iniFile.ReadValue("Device2", "status", System.IO.Path.GetFullPath("IniFile.ini"));
                    string resultOutput  = null;
                    if (device1Result == "-1" && device2Result == "-1")
                    {
                        resultOutput = "0";
                    }
                    else
                    {
                        resultOutput = "1";
                    }

                    ReceivedOutput = "621" + DateTime.Now.ToString("HHmmss") + "015" + "|" + content.Substring(13, 6) + "|" + resultOutput + "|01|02|";

                    if (device1Result != "-1")
                    {
                        bool result = IniFileHelper.WriteValue("Device1", "status", " 1", System.IO.Path.GetFullPath("IniFile.ini"));
                    }
                    if (device2Result != "-1")
                    {
                        bool results = IniFileHelper.WriteValue("Device2", "status", " 1", System.IO.Path.GetFullPath("IniFile.ini"));
                    }
                    break;

                case "612":
                    string device1Reset = iniFile.ReadValue("Device1", "status", System.IO.Path.GetFullPath("IniFile.ini"));
                    string device2Reset = iniFile.ReadValue("Device2", "status", System.IO.Path.GetFullPath("IniFile.ini"));
                    string resetOutput1 = null;
                    string resetOutput2 = null;
                    if (device1Reset == "-1")
                    {
                        resetOutput1 = "1";
                    }
                    else
                    {
                        resetOutput1 = "0";
                    }

                    if (device2Reset == "-1")
                    {
                        resetOutput2 = "1";
                    }
                    else
                    {
                        resetOutput2 = "0";
                    }
                    ReceivedOutput = "622" + DateTime.Now.ToString("HHmmss") + "010" + "|" + content.Substring(13, 6) + "|" + resetOutput1 + "|" + resetOutput2 + "|";

                    if (device1Reset != "-1")
                    {
                        bool result = IniFileHelper.WriteValue("Device1", "status", "0", System.IO.Path.GetFullPath("IniFile.ini"));
                    }
                    if (device2Reset != "-1")
                    {
                        bool results = IniFileHelper.WriteValue("Device2", "status", "0", System.IO.Path.GetFullPath("IniFile.ini"));
                    }
                    //modbusClient.Connect();
                    //modbusClient.WriteSingleCoil(0001, false);
                    //modbusClient.Disconnect();
                    break;

                case "619":
                    string device1Status = iniFile.ReadValue("Device1", "status", System.IO.Path.GetFullPath("IniFile.ini"));
                    string device2Status = iniFile.ReadValue("Device2", "status", System.IO.Path.GetFullPath("IniFile.ini"));

                    ReceivedOutput = "629" + DateTime.Now.ToString("HHmmss") + "011" + "|" + content.Substring(13, 6) + "|" + device1Status + "|" + device2Status + "|";
                    break;

                default:
                    ReceivedOutput = "invalid command code";
                    break;
                }

                // All the data has been read from the
                // client. Display it on the console.
                Console.WriteLine("Read {0} bytes from socket.\nData : {1}",
                                  content.Length, content);

                // Echo the data back to the client.
                Send(handler, ReceivedOutput + "\r");
            }
            else
            {
                // Not all data received. Get more.
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                     new AsyncCallback(ReadCallback), state);
            }
        }
    }
示例#56
0
            public static void ReadCallback(IAsyncResult ar)
            {
                String content = String.Empty;

                // Retrieve the state object and the handler socket
                // from the asynchronous state object.
                StateObject state   = (StateObject)ar.AsyncState;
                Socket      handler = state.workSocket;

                // Read data from the client socket.
                int bytesRead = handler.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // There  might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(
                                        state.buffer, 0, bytesRead));

                    // Check for end-of-file tag. If it is not there, read more data.
                    content = state.sb.ToString();
                    if (content.IndexOf("<EOF>") > -1)
                    {
                        // All the data has been read from the client. Display it on the console.
                        int x_start_ind = content.IndexOf("x: "), x_end_ind = content.IndexOf("xend ");
                        // int x_start_ind = content.IndexOf("x: "), x_end_ind = content.IndexOf("xend ");
                        // int y_start_ind = content.IndexOf("y: "), y_end_ind = content.IndexOf("yend ");

                        if (x_start_ind > -1 && x_end_ind > -1)
                        {
                            try
                            {
                                //convert the received string into x and y
                                // x_received = Convert.ToInt32(content.Substring(x_start_ind + 3, x_end_ind - (x_start_ind + 3)));
                                // y_received = Convert.ToInt32(content.Substring(y_start_ind + 3, y_end_ind - (y_start_ind + 3)));
                                string s = content.Substring(x_start_ind + 3, x_end_ind - (x_start_ind + 3));
                                //received_cards_arr = s.Split(',').Select(str => int.Parse(str)).ToArray(); ;
                                // received = Convert.ToInt32(content.Substring(x_start_ind + 3, x_end_ind - (x_start_ind + 3)));
                                received = s;
                            }
                            catch (FormatException)
                            {
                                Console.WriteLine("Input string is not a sequence of digits.");
                            }
                            catch (OverflowException)
                            {
                                Console.WriteLine("The number cannot fit in an Int32.");
                            }
                        }
                        // Show the data on the console.
                        //Console.WriteLine("x : {0}  y: {1}", x_received, y_received);

                        // Echo the data back to the client.
                        Send(handler, content);
                    }
                    else
                    {
                        // Not all data received. Get more.
                        handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                                             new AsyncCallback(ReadCallback), state);
                    }
                }
            }
示例#57
0
 protected abstract void OnRecieved(StateObject state);
 private void SimpleCallback(StateObject state)
 {
     state.Counter++;
     _callbackReceivedEvent.Set();
 }
示例#59
0
        private static void CreateArrowImageCell(StateObject stateObj, DataGridViewRow row, int cellIndex, ParserObject nextContinuedObj, ParserObject prevInterruptedObj)
        {
            var cell = new DataGridViewImageCell();

            if (stateObj == null)
            {
                row.Cells[cellIndex] = cell;
                return;
            }

            if (prevInterruptedObj != null)
            {
                var tag = new TagArrowInfo {
                    refObj = prevInterruptedObj, stateObj = stateObj
                };
                if (IsArrowClickable(tag))
                {
                    cell.Value      = ImageExt.ColorReplace(Properties.Resources.forward_arrow, Color.White, ColorTranslator.FromHtml(prevInterruptedObj.BaseColor));
                    tag.IsClickable = true;
                    tag.ToolTipText = "To PREVIOUS state...";
                    cell.Tag        = tag;
                }
                else
                {
                    cell.Value      = Properties.Resources.forward_arrow;
                    tag.IsClickable = false;
                    cell.Tag        = new TagArrowInfo {
                        refObj = null, stateObj = stateObj
                    };
                }
            }
            else if (nextContinuedObj != null)
            {
                var tag = new TagArrowInfo {
                    refObj = nextContinuedObj, stateObj = stateObj
                };
                if (IsArrowClickable(tag))
                {
                    cell.Value      = ImageExt.ColorReplace(Properties.Resources.forward_arrow, Color.White, ColorTranslator.FromHtml(nextContinuedObj.BaseColor));
                    tag.IsClickable = true;
                    tag.ToolTipText = "To NEXT state...";
                    cell.Tag        = tag;
                }
                else
                {
                    cell.Value      = Properties.Resources.forward_arrow;
                    tag.IsClickable = false;
                    cell.Tag        = new TagArrowInfo {
                        refObj = null, stateObj = stateObj
                    };
                }
            }
            else
            {
                cell.Value = Properties.Resources.forward_arrow;
                cell.Tag   = new TagArrowInfo {
                    refObj = null, stateObj = stateObj
                };
            }

            row.Cells[cellIndex] = cell;
        }
示例#60
0
        void ConnectToHostAndSendRequest <T>(bool sslEnabled, TcpClient tcpClient, RequestState <T> pubnubRequestState, string requestString)
        {
            NetworkStream stream = tcpClient.GetStream();

            string proxyAuth = string.Format("{0}:{1}", Proxy.ProxyUserName, Proxy.ProxyPassword);

            byte[] proxyAuthBytes = Encoding.UTF8.GetBytes(proxyAuth);

            //Proxy-Authenticate: authentication mode Basic, Digest and NTLM
            string connectRequest = "";

            if (sslEnabled)
            {
                connectRequest = string.Format("CONNECT {0}:443  HTTP/1.1\r\nProxy-Authorization: Basic {1}\r\nHost: {0}\r\n\r\n", this._domainName, Convert.ToBase64String(proxyAuthBytes));
            }
            else
            {
                connectRequest = string.Format("CONNECT {0}:80  HTTP/1.1\r\nProxy-Authorization: Basic {1}\r\nHost: {0}\r\n\r\n", this._domainName, Convert.ToBase64String(proxyAuthBytes));
            }

            byte[] tunnelRequest = Encoding.UTF8.GetBytes(connectRequest);
            stream.Write(tunnelRequest, 0, tunnelRequest.Length);
            stream.Flush();

            stream.ReadTimeout = pubnubRequestState.Request.Timeout * 5;

            StateObject <T> state = new StateObject <T>();

            state.tcpClient     = tcpClient;
            state.RequestState  = pubnubRequestState;
            state.requestString = requestString;
            state.netStream     = stream;

            //stream.BeginRead(state.buffer, 0, state.buffer.Length, new AsyncCallback(ConnectToHostAndSendRequestCallback<T>), state);

            StringBuilder response       = new StringBuilder();
            var           responseStream = new StreamReader(stream);

            char[] buffer = new char[2048];

            int  charsRead       = responseStream.Read(buffer, 0, buffer.Length);
            bool connEstablished = false;

            while (charsRead > 0)
            {
                response.Append(buffer);
                if ((response.ToString().IndexOf("200 Connection established") > 0) || (response.ToString().IndexOf("200 OK") > 0))
                {
                    connEstablished = true;
                    break;
                }
                charsRead = responseStream.Read(buffer, 0, buffer.Length);
            }

            if (connEstablished)
            {
                if (sslEnabled)
                {
                    SendSslRequest <T>(stream, tcpClient, pubnubRequestState, requestString);
                }
                else
                {
                    SendRequest <T>(tcpClient, pubnubRequestState, requestString);
                }
            }
            else if (response.ToString().IndexOf("407 Proxy Authentication Required") > 0)
            {
                int    pos  = response.ToString().IndexOf("Proxy-Authenticate");
                string desc = "";
                if (pos > 0)
                {
                    desc = response.ToString().Substring(pos, response.ToString().IndexOf("\r\n", pos) - pos);
                }
                throw new WebException(string.Format("Proxy Authentication Required. Desc: {0}", desc));
            }
            else
            {
                throw new WebException("Couldn't connect to the server");
            }
        }