Asychronous server socket problem

Discussion in '.NET' started by cmrhema, Aug 7, 2008.

  1. cmrhema

    cmrhema

    Joined:
    Aug 21, 2007
    Messages:
    2
    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
                    {
                      [U][B]  sock.Disconnect(false);
                        sock.Close();
                        stateobject = null;
                        Console.WriteLine("Inside infinite loop");
                        socketClosed = true;[/B][/U]
                     }
                    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
    cmrhema, Aug 7, 2008
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ruth
    Replies:
    1
    Views:
    1,408
    Tim Hubberstey
    Jun 26, 2003
  2. yali
    Replies:
    2
    Views:
    734
    anupam
    Aug 31, 2004
  3. Frank Mamone
    Replies:
    2
    Views:
    472
    Frank Mamone
    Sep 14, 2004
  4. SenthilVel

    how to use asychronous calls

    SenthilVel, May 15, 2006, in forum: ASP .Net
    Replies:
    0
    Views:
    406
    SenthilVel
    May 15, 2006
  5. utabintarbo
    Replies:
    8
    Views:
    312
    utabintarbo
    Oct 11, 2006
Loading...

Share This Page