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

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

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

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

--------------------------------------------------------------------------------------------------------------------------

This i my program when i run this program then i show the card the card detail will come to my output page here i mentioned (boldlines red color comment see that)


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;


namespace TCPIP
{
public partial class Form1 : Form
{
//Establish the local endpoint for the socket
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("192.168.1.201"), 4370); // here i declared fetching for IP address
//Create a TCPIP socket
Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

public Form1()
{
InitializeComponent();
}


private void btnConnect_Click(object sender, EventArgs e)
{
try
{
soc.Connect(ip); //socket connected // here am passed that opject its syntax correct or not please check
byte[] data = new byte[1024];
soc.Receive(data);
//int length=BitConverter.ToInt32(data,0);
string sD = Encoding.ASCII.GetString(data, 0,length);
MessageBox.Show(sD);
}
catch (SocketException excp)
{
MessageBox.Show(excp.Message);
return;
}
}
}


can you please check this code have any changes please mail me

jagamca.cs@gmail.com
its access control RFID card using door open system

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.