Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > ASP .Net > Asychronous server socket problem

Reply
Thread Tools

Asychronous server socket problem

 
 
cmrhema cmrhema is offline
Junior Member
Join Date: Aug 2007
Posts: 2
 
      08-07-2008
Hi,
We have an asynchronous server socket program, which works fine BUT, when due to some circumstances, I receive null data or blank data, the server goes to infinite loop
Here is the code



Code:
namespace SocketServer
{

    public class StateObject  //class created to clear the duplicate records
    {
        // Client socket.
        public Socket workSocket = null;
        // Size of receive buffer.
        public const int BufferSize = 5000;
        // Receive buffer.
        public byte[] buffer = new byte[BufferSize];
        // Received data string.
        public string sb;

    }

    class Program
    {


        public AsyncCallback pfnWorkerCallBack;
        private Socket m_mainSocket;
       
        public int port = 7030;
        public byte[] m_byBuff = new byte[5000];
        public int flag2 = 0;

        public byte[] inValue = new byte[] { 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 };
        public byte[] outvalue = new byte[10];

        private string m_strConnection;
        public Program()
        {
            this.m_strConnection = ConfigurationSettings.AppSettings["Connection"];
            this.strDateFormat = null;
            this.strLocation = null;
            StartListen();


        }
        public void StartListen()
        {


            try
            {
                NameValueCollection collection1 = ConfigurationSettings.AppSettings;
                m_mainSocket = new Socket(AddressFamily.InterNetwork,
                                          SocketType.Stream,
                                          ProtocolType.Tcp);
                IPAddress ip;

                string ipstr = "198.158.0.20";

                ip = IPAddress.Parse(ipstr);

                IPEndPoint ipLocal = new IPEndPoint(ip, 7030);
                m_mainSocket.Bind(ipLocal);
                m_mainSocket.Listen(100);

               // Create the call back for any client connections...

               
                while (true)
                {
                    m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
                    Thread.Sleep(1000);
                }
              
            }
            catch (Exception e1)
            {
                Console.WriteLine(e1.Message.ToString());
                WriteErrorLogMessage(e1.Message);
              

            }
        }
    

        public void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
               Socket msocket;
                msocket = m_mainSocket.EndAccept(asyn);
                msocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, 1);
                msocket.IOControl(IOControlCode.KeepAliveValues, inValue, outvalue);
               WaitForData(msocket);
            }

            catch (Exception e1)
            {
                Console.WriteLine(e1.Message.ToString());
                WriteErrorLogMessage(e1.Message);
            }

        }


        public void WaitForData(System.Net.Sockets.Socket soc)
        {
            try
            {
                if (pfnWorkerCallBack == null)
                {
                     pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
                }
               
                StateObject state = new StateObject();
                state.workSocket = soc;
                soc.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, pfnWorkerCallBack, state);
              
            }
            catch (Exception e1)
            {
                Console.WriteLine(e1.Message.ToString());
                WriteErrorLogMessage(e1.Message);
            }

        }
        public void OnDataReceived(IAsyncResult asyn)
        {
            Console.WriteLine("data received");
            WriteLogMessage("data received");
            bool socketClosed = false;
            try
            {
                StateObject stateobject = (StateObject)asyn.AsyncState;
                Socket sock = stateobject.workSocket;//assgning the app socket to new socket
        
                int nBytesRec = sock.EndReceive(asyn);

                if (nBytesRec > 0)
                {
                    string sReceived = System.Text.Encoding.ASCII.GetString(stateobject.buffer, 0, StateObject.BufferSize);
                    
                    sReceived = sReceived.TrimEnd('\0');
                    WriteLogMessage(sReceived);
                   if (sReceived != null && sReceived != " " && sReceived != "")
                    {
                       Console.WriteLine(sReceived);
                }
                  
                else
                {
                    sock.Disconnect(false);
                    sock.Close();
                    stateobject = null;
                    Console.WriteLine("Inside infinite loop");
                    socketClosed = true;
                 }
                if (!socketClosed)
                {
                    byte[] Buffer = new byte[StateObject.BufferSize];

                    stateobject.buffer = Buffer;

                    sock.BeginReceive(stateobject.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(OnDataReceived), stateobject);
                }
            }

            catch (SocketException e1)
            {
                Console.WriteLine(e1.Message.ToString());
                WriteErrorLogMessage(e1.Message);
            }


            catch (Exception e1)
            {
                Console.WriteLine("Inside infinite loop");
                WriteErrorLogMessage(e1.Message);
            }
        }

There is an underlined code, where we want to disconnect those socket connections which does not carry any value. When we did that what happens is, whenever the socket reconnects it does not connect, nor does any other live socket connects.


Please let me know where are we going wrong
Thanks in advance
Regards
cmrhema
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Asychronous execution *with* return codes? utabintarbo Python 8 10-11-2006 11:49 AM
how to use asychronous calls SenthilVel ASP .Net 0 05-15-2006 02:10 PM
Problem with Asychronous Web Service Callback Frank Mamone ASP .Net 2 09-14-2004 01:39 PM
asychronous sram read and write yali VHDL 2 08-31-2004 05:11 AM
multiple asychronous resets Ruth VHDL 1 06-26-2003 06:01 PM



Advertisments