How to listen socket in single ASP page?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • x0rn
    New Member
    • Feb 2014
    • 3

    How to listen socket in single ASP page?

    I am developing client-server application using TCP Socekts and C#. I need to send message from console application to ASP page. I can connect from ASP page using OnLoad event and sometimes on PageLoad event I can receive several messages only. I have 2 questions:
    1. How to listen continuously the server socket and receive messages?
    2. How to know when the ASP page closed (by user) to disconnect from server?

    Console ServerApp

    Code:
     static void StartServer()
        {
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 1000);
     
            serverSocket.Bind(ipEndPoint);
            serverSocket.Listen(4);
     
            ConsoleKeyInfo cki;
            XmlDocument doc = new XmlDocument();
     
            doc.Load("test.xml");
            serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);
     
            Console.WriteLine("Server started " + DateTime.Now + Environment.NewLine);
            Console.WriteLine("Press S to start Data Sharing or ESC key to quit" + Environment.NewLine);            
     
            do
            {
                cki = Console.ReadKey();
     
                if (cki.Key == ConsoleKey.S)
                {                    
                    foreach (XmlNode node in doc.DocumentElement.ChildNodes)
                    {
                        try
                        {
                            _client = (ClientInfo)clientList[0];
                            if (((ClientInfo)clientList[0]).strName == node.Attributes["type"].InnerText)
                            {
                                SendRecord(node.Attributes["type"].InnerText + node.Attributes["value"].InnerText, (ClientInfo)clientList[0]);
                                clientList.Insert(clientList.Count, (ClientInfo)clientList[0]);
                                clientList.RemoveAt(0);
                            }
                        }
     
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.message);
                        }
                    }
                    Console.WriteLine("Data sharing finished " + DateTime.Now);
                }
     
            } while (cki.Key != ConsoleKey.Escape);
        }        
     
        static void SendRecord(string _msg, ClientInfo client)
        {
            Data msgToSend = new Data();
            msgToSend.cmdCommand = Command.Message;
            msgToSend.strMessage = _msg;
            byte[] byteData = msgToSend.ToByte();
     
            try
            {
                client.socket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnSend), _client);
                Thread.Sleep(3);
            }
     
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    ASP Client side:

    Code:
     protected void Page_Load(object sender, EventArgs e)
    {        
        if (!IsPostBack)
            Connect();
    }
     
    protected void Page_OnClose(object sender, EventArgs e)
    {
        Disconnect();
    }
     
    protected void updateEvent(object sender, EventArgs e)
    {
        if (msglist.Count > 0) lstRecords.Items.Add(msg);
        lstRecords.Height = Unit.Percentage(100);     
    }
     
    
    private void Connect()
    {
        Data msgToSend = new Data();
     
        IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
        IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1000);
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     
        msgToSend.strType = strType;
        msgToSend.strMessage = null;
        msgToSend.cmdCommand = Command.List;
     
        byteData = msgToSend.ToByte();
     
        try
        {
            clientSocket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), null);
            clientSocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
     
            byteData = new byte[1024];
            clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
        }
     
        catch (Exception ex)
        {
            lstRecords.Items.Add(ex.Message);
        }
    }
    Server App is sending to WinApp and ConsoleApp without any problem. But with ASP page, I can correctly receive only Connect message and sometimes i can receive 1-2-3 msg only. I am using javascript
    Code:
    setInterval("__doPostBack('upDynamicClock', '');", 1000);
    to do refresh.

    ASP .NET page life-cycle has several stages. I am confused which one i have to use to receive data contentiously and update control at the same time? Or it's impossible?
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    To understand the ASP.NET life cycle you should probably read the documentation provided by Microsoft on the topic. You can find this documentation in the MSDN Library. For example, this is a good over view for the ASP.NET Life Cycle.

    Anyways, you should probably consider creating a web service application instead of an ASP.NET Forums application.

    Comment

    • x0rn
      New Member
      • Feb 2014
      • 3

      #3
      Solved

      Solved.
      HTTP is stateless, ASP.NET WebForms only tries to hide this with viewstate and such. As soon as you see the page in your browser, the page isn't alive anymore and your OnSend callback won't be called anymore. This is also explained in Create web page with live socket based data.

      If your goal is to update an HTML element with server-fed data, take a look at SignalR.

      http://stackoverflow.com/questions/2...33934_21873956[^]

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        I'm glad you figured it out!
        Thanks for sharing your solution.

        Comment

        Working...