Пример #1
0
        public static Message CreateFromByteArray(byte[] data)
        {
            //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-gb");
            //Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

            //
            // SOAP Serializer
            Message msg = null;

            try
            {
                //SoapFormatter soap = new SoapFormatter();
                XmlSerializer soap = new XmlSerializer(typeof(Message));
                MemoryStream  ms   = new MemoryStream(data);
                object        dso  = soap.Deserialize(ms);

                try
                {
                    msg = (Message)dso;
                }
                catch (Exception ef)
                {
                    Audit.WriteLine("type=" + dso.GetType() + " cast to Message threw exception " + ef);
                    return(null);
                }
                ms.Close();
            }
            catch (Exception ee)
            {
                Audit.WriteLine("Message serialization failed, error=" + ee.ToString());
                return(null);
            }
            Audit.WriteLine("Message type= " + msg.GetType());
            return(msg);
        }
Пример #2
0
        public void Disconnect()
        {
            if (mSocket != null)
            {
                Socket mTemp = mSocket;
                mSocket = null;
                Audit.WriteLine("start close");


                try
                {
                    mTemp.Blocking = true;

                    if (mTemp.Connected)
                    {
                        mTemp.Close();
                    }
                }
                catch (Exception)
                {
                }
                Audit.WriteLine("stop close - all async handlers should be disconnected by now");
                if (OnNotify != null)
                {
                    OnNotify("Disconnect", null);
                }
            }
            mSocket = null;
        }
Пример #3
0
        private void ConnectCallback(IAsyncResult ar)
        {
            Socket newSocket = null;

            try
            {
                try
                {
                    newSocket = mSocket.EndAccept(ar);
                }
                catch (System.ObjectDisposedException)
                {
                    //Console.WriteLine("Server socket error - ConnectCallback failed "+ee.Message);
                    mSocket = null;
                    return;
                }

                try
                {
                    Audit.WriteLine("Connection received - call OnConnect");
                    //
                    if (this.OnConnectRAW != null)
                    {
                        this.OnConnectRAW(newSocket);
                    }
                    //
                    if (this.OnConnect != null)
                    {
                        ClientSocket socket = new ClientSocket(newSocket);
                        socket.FXSocketType = this.mSocketType;
                        this.OnConnect(socket);
                    }

                    // restart accept
                    mSocket.BeginAccept(callbackProc, null);
                }
                catch (System.ObjectDisposedException)
                {
                    newSocket.Close();
                    newSocket = null;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception occured in AcceptCallback\n" + e);
                    newSocket.Close();
                    newSocket = null;
                }
            }
            finally
            {
                // wait for the next incoming connection
                if (mSocket != null)
                {
                    mSocket.BeginAccept(callbackProc, null);
                }
            }
        }
Пример #4
0
 public ClientSocket()
 {
     // Workaround for bug in IE hosted controls that means they take 100 seconds
     // to connect to TCP/IP.
     //
     ConfigurationManager.AppSettings.Get("DNS");
     //
     Audit.WriteLine("Client socket created.");
     info();
 }
Пример #5
0
 public void Start()
 {
     Audit.WriteLine("sock.start");
     if (mSocket.Connected)
     {
         mSocket.Blocking = false;
         mState           = State.Waiting;
         AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
         mSocket.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, mSocket);
         Audit.WriteLine("called begin receive");
     }
     else
     {
         Audit.WriteLine("bugbug-- not connected");
         throw new ApplicationException("Socket passed to us, but not connected to anything");
     }
 }
Пример #6
0
 private void ConnectCallback(IAsyncResult ar)
 {
     try
     {
         Audit.WriteLine("connect async notifier");
         // Get The connection socket from the callback
         Socket sock1 = (Socket)ar.AsyncState;
         if (sock1.Connected)
         {
             // notify parent here
             if (this.OnNotify != null)
             {
                 this.OnNotify("Connect", null);
             }
             //
             // Define a new Callback to read the data
             AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
             // Begin reading data asyncronously
             sock1.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, sock1);
             Audit.WriteLine("setup data receiver");
         }
         else
         {
             // notify parent - connect failed
             if (this.OnNotify != null)
             {
                 this.OnNotify("ConnectFailed", null);
             }
             Audit.WriteLine("Connect failed");
         }
     }
     catch (Exception ex)
     {
         Audit.WriteLine("Setup Receive callback failed " + ex);
         throw;
     }
 }
Пример #7
0
 public void info()
 {
     Audit.WriteLine("CLRVersion = " + Environment.Version);
     Audit.WriteLine("UserName   = "******"Assembly version = " + typeof(ClientSocket).Assembly.FullName);
 }
Пример #8
0
        private void OnRecievedData(IAsyncResult ar)
        {
            //Audit.WriteLine("OnReceivedData");
            // Get The connection socket from the callback
            Socket sock = (Socket)ar.AsyncState;

            // is socket closing
            if (!sock.Connected)
            {
                return;
            }
            // Get The data , if any
            int nBytesRec = 0;

            try
            {
                nBytesRec = sock.EndReceive(ar);
            }
            catch (System.ObjectDisposedException)
            {
                Console.WriteLine("Client socket OnReceived data received socket disconnect (object disposed)");
                nBytesRec = 0;
                OnData(null, 0);                // notify close
                return;
            }
            catch (System.Net.Sockets.SocketException se)
            {
                Console.WriteLine("Client socket OnReceived data received socket disconnect (" + se.Message + ")");
                nBytesRec = 0;
                OnData(null, 0);                // notify close
                return;
            }
            //Audit.WriteLine("OnReceivedData bytes="+nBytesRec);
            if (OnData != null && nBytesRec > 0)
            {
                OnData(m_byBuff, nBytesRec);
            }
            if (nBytesRec > 0)
            {
                // process it if we're a client server socket
                if (mSocketType == ServerSocketType.ClientServer)
                {
                    for (int i = 0; i < nBytesRec; i++)
                    {
                        switch (mState)
                        {
                        case State.Waiting:
                            currentBuffer      = new byte[MessageHeader.MessageHeaderSize];
                            currentBufferIndex = 0;
                            currentBuffer[currentBufferIndex++] = m_byBuff[i];
                            mState = State.ReadingHeader;
                            break;

                        case State.ReadingHeader:
                            currentBuffer[currentBufferIndex++] = m_byBuff[i];
                            if (currentBufferIndex >= MessageHeader.MessageHeaderSize)
                            {
                                currentMessageHeader = new MessageHeader(currentBuffer);
                                currentBuffer        = new byte[currentMessageHeader.uMessageSize];
                                currentBufferIndex   = 0;
                                mState = State.ReadingBuffer;
                            }
                            break;

                        case State.ReadingBuffer:
                            currentBuffer[currentBufferIndex++] = m_byBuff[i];
                            if (currentBufferIndex >= currentMessageHeader.uMessageSize)
                            {
                                string dump = System.Text.Encoding.Default.GetString(currentBuffer);
                                Audit.WriteLine("RCLRVersion = " + Environment.Version);
                                Audit.WriteLine("Writeline " + dump);
                                try
                                {
                                    Message msg = Message.CreateFromByteArray(currentBuffer);
                                    if (msg != null && this.OnNotify != null)
                                    {
                                        this.OnNotify("Data", msg);
                                    }
                                }
                                catch (Exception e)
                                {
                                    Audit.WriteLine("Exception handling message " + e);
                                }
                                mState = State.Waiting;
                            }
                            break;

                        default:
                            throw new ApplicationException("sorry, state '" + mState + "' not known");
                        }
                    }
                }
                //
                //
                try
                {
                    // Define a new Callback to read the data
                    AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
                    // Begin reading data asyncronously
                    mSocket.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, mSocket);
                    //
                }
                catch (Exception e)
                {
                    // assume socket was disconnected somewhere else if an exception occurs here
                    Audit.WriteLine("Socket BeginReceived failed with error " + e.Message);
                    Disconnect();
                }
            }
            else
            {
                // If no data was recieved then the connection is probably dead
                Audit.WriteLine("Socket was disconnected disconnected");                 //+ sock.RemoteEndPoint );
                Disconnect();
            }
        }
Пример #9
0
        public void Connect(string address, int port)
        {
            Audit.WriteLine("Connect " + address + " -- " + port);
            Disconnect();
            mState = State.Waiting;
            //
            // permissions
            SocketPermission mySocketPermission1 = new SocketPermission(PermissionState.None);

            mySocketPermission1.AddPermission(NetworkAccess.Connect, TransportType.All, "localhost", 8800);
            mySocketPermission1.Demand();

            //
            // Actually connect
            //
            // count .s, numeric and 3 .s =ipaddress
            bool ipaddress = false;
            bool text      = false;
            int  count     = 0;
            int  i;

            for (i = 0; i < address.Length; i++)
            {
                if (address[i] == '.')
                {
                    count++;
                }
                else
                {
                    if (address[i] < '0' || address[i] > '9')
                    {
                        text = true;
                    }
                }
            }
            if (count == 3 && text == false)
            {
                ipaddress = true;
            }

            if (!ipaddress)
            {
                Audit.WriteLine("Dns.Resolve " + address);
                IPHostEntry IPHost  = Dns.GetHostEntry(address);
                string []   aliases = IPHost.Aliases;
                IPAddress[] addr    = IPHost.AddressList;
                iep = new IPEndPoint(addr[0], port);
            }
            else
            {
                Audit.WriteLine("Use address " + address + " as ip");
                iep = new IPEndPoint(IPAddress.Parse(address), port);
            }


            try
            {
                // Create New Socket
                mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                // Create New EndPoint
                // This is a non blocking IO
                mSocket.Blocking = false;
                // set some random options
                //
                //mSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1);

                //
                // Assign Callback function to read from Asyncronous Socket
                callbackProc = new AsyncCallback(ConnectCallback);
                // Begin Asyncronous Connection
                mSocket.BeginConnect(iep, callbackProc, mSocket);
            }
            catch (Exception eeeee)
            {
                Audit.WriteLine("e=" + eeeee);
                throw;
                //				st_changed(STCALLBACK.ST_CONNECT, false);
            }
        }
Пример #10
0
 public ClientSocket()
 {
     Audit.WriteLine("Client socket created.");
     info();
 }