• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 595
  • Last Modified:

Sockets Async

Why is my event not firing ? Event "OnDataReceived"
Am I doing something wrong ?
class TCP_IP : Connection
    {
 
        Socket mSocket;
        IPEndPoint mIPEndPoint;
        //byte[] m_DataBuffer = new byte[10];
        IAsyncResult m_asynResult;
        public AsyncCallback pfnCallBack;
                
        public int ReceiveTimeout = 500;
        public int SendTimeout = 500;
        public string IPAddress = "";
        public int Port = 0;
 
 
        //If Connected
        public override bool IsConnected
        {
            get
            {
                bool b = false;
                if (mSocket != null)
                    b = mSocket.Connected;
 
                return b;
            }
        }
 
        //The amount of bytes a Buffer should expect when reading
        private int _byteToRead;
        public override int byteToRead
        {
            get
            {
                return _byteToRead;
            }
            set
            {
                _byteToRead = value;
            }
        }
 
        public override bool Connect()
        {
            if (!IsConnected)
            {
                if (mSocket == null)
                    mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                if (mIPEndPoint == null)
                    mIPEndPoint = new IPEndPoint(System.Net.IPAddress.Parse(IPAddress), Port);
 
 
                mIPEndPoint.Address = System.Net.IPAddress.Parse(IPAddress);
                mIPEndPoint.Port = Port;
                //mSocket.Blocking = false;
                //mSocket.Bind(mIPEndPoint);
                //mSocket.Listen(32);
                mSocket.ReceiveTimeout = ReceiveTimeout;
                mSocket.SendTimeout = SendTimeout;
                
                try
                {                   
                    mSocket.Connect(mIPEndPoint);
                    WaitForData();
                    
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            return true;                      
        }
 
        void sPort_DataReceived()
        {
            ReadData();
        }
 
 
        public override void Disconnect()
        {
            //mSocket.Disconnect(true);//Reuse Socket
        }
 
        byte[] buffer = null;
        public override void SendData(string data)
        {
            buffer = ASCIIEncoding.ASCII.GetBytes(data);         
            mSocket.Send(buffer);
            //Thread.Sleep(100);
        }
 
        public override void SendData(byte[] data)
        {
            mSocket.Send(data);
        }
 
 
        public override List<byte> ReadData()
        {
            List<byte> myList = new List<byte>();
 
 
 
            return myList;       
    
        }
        
      
        public void WaitForData()
        {
            if (pfnCallBack == null)
                pfnCallBack = new AsyncCallback(OnDataReceived);
            // now start to listen for any data...
            m_asynResult = mSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, pfnCallBack, null);
        }
        public void OnDataReceived(IAsyncResult asyn)
        {
            //end receive...
            int iRx = 0;
            iRx = mSocket.EndReceive(asyn);
            char[] chars = new char[iRx + 1];
            System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
            int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
            System.String szData = new System.String(chars);
            WaitForData();
        }
 
 
    }

Open in new window

0
u2envy1
Asked:
u2envy1
  • 2
1 Solution
 
gregoryyoungCommented:
There are quite a few threading problems here (everything send/receive is all using the same buffer).

Beyond that I never see where you intiialize

byte[] buffer = null;

So you would die on your call to BeginReceive

Greg
0
 
u2envy1Author Commented:
Does this look better ?
Im able to send data but not recieve.
Im now getting an error :  An existing connection was forcibly closed by the remote host
The Error happens here........
// now start to listen for any data...            
            m_asynResult = mSocket.BeginReceive(m_DataBuffer, 0, m_DataBuffer.Length, SocketFlags.None, pfnCallBack, null);
  class TCP_IP : Connection
    {
 
        Socket mSocket;
        IPEndPoint mIPEndPoint;
        IAsyncResult m_asynResult;
        public AsyncCallback pfnCallBack;
 
        public int ReceiveTimeout = 500;
        public int SendTimeout = 500;
        public string IPAddress = "";
        public int Port = 0;
 
 
        //If Connected
        public override bool IsConnected
        {
            get
            {
                bool b = false;
                if (mSocket != null)
                    b = mSocket.Connected;
 
                return b;
            }
        }
 
        //The amount of bytes a Buffer should expect when reading
        private int _byteToRead;
        public override int byteToRead
        {
            get
            {
                return _byteToRead;
            }
            set
            {
                _byteToRead = value;
            }
        }
 
        public override bool Connect()
        {
            if (!IsConnected)
            {
                if (mSocket == null)
                    mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                if (mIPEndPoint == null)
                    mIPEndPoint = new IPEndPoint(System.Net.IPAddress.Parse(IPAddress), Port);
 
 
                mIPEndPoint.Address = System.Net.IPAddress.Parse(IPAddress);
                mIPEndPoint.Port = Port;
                //mSocket.Blocking = false;
                //mSocket.Bind(mIPEndPoint);
                //mSocket.Listen(32);
                mSocket.ReceiveTimeout = ReceiveTimeout;
                mSocket.SendTimeout = SendTimeout;
 
                try
                {
                    // pfnCallBack = new AsyncCallback(OnDataReceived);
                    // mSocket.BeginConnect(mIPEndPoint, pfnCallBack, mSocket);
                    mSocket.Connect(mIPEndPoint);
                    WaitForData();
 
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            return true;
        }
 
        void sPort_DataReceived()
        {
            ReadData();
        }
 
 
        public override void Disconnect()
        {
            //mSocket.Disconnect(true);//Reuse Socket
        }
 
        byte[] buffer = null;
        public override void SendData(string data)
        {
            //Connect();
            try
            {
                buffer = ASCIIEncoding.UTF8.GetBytes(data);//Convert to UTF8 to communicate with Unibadger
                int bLen = buffer.Length;
                buffer[1] = (Convert.ToByte((char)191));//Add for TCP/IP Starting Values
                buffer[2] = (Convert.ToByte((char)1));//Add for TCP/IP Starting Values
 
                byte[] bufferNew = new byte[bLen + 1];//Create array to hold new values plus 1 added values
 
                Array.Copy(buffer, 1, bufferNew, 0, bLen - 1);//Remove the first array[0] & add the rest to bufferNew
                bufferNew[bLen - 1] = (Convert.ToByte((char)1));//Add end values for TCP/IP Ending Values
                bufferNew[bLen] = (Convert.ToByte((char)1));//Add end values for TCP/IP Ending Values
                mSocket.Send(bufferNew);
                mSocket.Listen(5000);
                mSocket.BeginAccept(OnDataReceived, mSocket);
                //Thread.Sleep(10);
                //ReadData();
                //mSocket.BeginSend(buffer);
            }
            catch (SocketException se)
            {
                string err = se.ToString();
            }
 
        }
 
        public override void SendData(byte[] data)
        {
            mSocket.Send(data);
        }
 
 
        public override List<byte> ReadData()
        {
            List<byte> myList = new List<byte>();
 
           
            return myList;              
 
        }
 
        byte[] m_DataBuffer;
        public void WaitForData()
        {
            m_DataBuffer = new byte[256];
            if (pfnCallBack == null)
                pfnCallBack = new AsyncCallback(OnDataReceived);
            // now start to listen for any data...            
            m_asynResult = mSocket.BeginReceive(m_DataBuffer, 0, m_DataBuffer.Length, SocketFlags.None, pfnCallBack, null);
        }
        public void OnDataReceived(IAsyncResult asyn)
        {
            //end receive...
            int iRx = 0;
            try
            {
                iRx = mSocket.EndReceive(asyn);
                char[] chars = new char[iRx + 1];
                System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
                int charLen = d.GetChars(m_DataBuffer, 0, iRx, chars, 0);
                System.String szData = new System.String(chars);
            }
            catch (SocketException)
            {
 
            }
 
            WaitForData();
        }
 
 
    }

Open in new window

0
 
gregoryyoungCommented:
thats the remote server closing the connection for whatever reason ...
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now