473,387 Members | 1,572 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

How to listen socket in single ASP page?

3
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

Expand|Select|Wrap|Line Numbers
  1.  static void StartServer()
  2.     {
  3.         serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  4.         IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 1000);
  5.  
  6.         serverSocket.Bind(ipEndPoint);
  7.         serverSocket.Listen(4);
  8.  
  9.         ConsoleKeyInfo cki;
  10.         XmlDocument doc = new XmlDocument();
  11.  
  12.         doc.Load("test.xml");
  13.         serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);
  14.  
  15.         Console.WriteLine("Server started " + DateTime.Now + Environment.NewLine);
  16.         Console.WriteLine("Press S to start Data Sharing or ESC key to quit" + Environment.NewLine);            
  17.  
  18.         do
  19.         {
  20.             cki = Console.ReadKey();
  21.  
  22.             if (cki.Key == ConsoleKey.S)
  23.             {                    
  24.                 foreach (XmlNode node in doc.DocumentElement.ChildNodes)
  25.                 {
  26.                     try
  27.                     {
  28.                         _client = (ClientInfo)clientList[0];
  29.                         if (((ClientInfo)clientList[0]).strName == node.Attributes["type"].InnerText)
  30.                         {
  31.                             SendRecord(node.Attributes["type"].InnerText + node.Attributes["value"].InnerText, (ClientInfo)clientList[0]);
  32.                             clientList.Insert(clientList.Count, (ClientInfo)clientList[0]);
  33.                             clientList.RemoveAt(0);
  34.                         }
  35.                     }
  36.  
  37.                     catch (Exception ex)
  38.                     {
  39.                         Console.WriteLine(ex.message);
  40.                     }
  41.                 }
  42.                 Console.WriteLine("Data sharing finished " + DateTime.Now);
  43.             }
  44.  
  45.         } while (cki.Key != ConsoleKey.Escape);
  46.     }        
  47.  
  48.     static void SendRecord(string _msg, ClientInfo client)
  49.     {
  50.         Data msgToSend = new Data();
  51.         msgToSend.cmdCommand = Command.Message;
  52.         msgToSend.strMessage = _msg;
  53.         byte[] byteData = msgToSend.ToByte();
  54.  
  55.         try
  56.         {
  57.             client.socket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnSend), _client);
  58.             Thread.Sleep(3);
  59.         }
  60.  
  61.         catch (Exception ex)
  62.         {
  63.             Console.WriteLine(ex.Message);
  64.         }
  65.     }
ASP Client side:

Expand|Select|Wrap|Line Numbers
  1.  protected void Page_Load(object sender, EventArgs e)
  2. {        
  3.     if (!IsPostBack)
  4.         Connect();
  5. }
  6.  
  7. protected void Page_OnClose(object sender, EventArgs e)
  8. {
  9.     Disconnect();
  10. }
  11.  
  12. protected void updateEvent(object sender, EventArgs e)
  13. {
  14.     if (msglist.Count > 0) lstRecords.Items.Add(msg);
  15.     lstRecords.Height = Unit.Percentage(100);     
  16. }
  17.  
  18.  
  19. private void Connect()
  20. {
  21.     Data msgToSend = new Data();
  22.  
  23.     IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
  24.     IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1000);
  25.     clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  26.  
  27.     msgToSend.strType = strType;
  28.     msgToSend.strMessage = null;
  29.     msgToSend.cmdCommand = Command.List;
  30.  
  31.     byteData = msgToSend.ToByte();
  32.  
  33.     try
  34.     {
  35.         clientSocket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), null);
  36.         clientSocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
  37.  
  38.         byteData = new byte[1024];
  39.         clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
  40.     }
  41.  
  42.     catch (Exception ex)
  43.     {
  44.         lstRecords.Items.Add(ex.Message);
  45.     }
  46. }
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
Expand|Select|Wrap|Line Numbers
  1. 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?
Feb 19 '14 #1
3 1903
Frinavale
9,735 Expert Mod 8TB
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.
Feb 20 '14 #2
x0rn
3
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[^]
Feb 21 '14 #3
Frinavale
9,735 Expert Mod 8TB
I'm glad you figured it out!
Thanks for sharing your solution.
Feb 26 '14 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: iMedia User | last post by:
I have a site where I want to use the Web form validators in two separate forms on a single page. One form allows existing users to log in while the second one allows new users to register. The...
4
by: Adrijan Josic | last post by:
I have this idea, I need to know if it is possible and how. Let's say you have a content managed site with all its structure and content - everything in a relational database And a "blank" page...
3
by: Ben Fidge | last post by:
Is is possible to make just a single page within an ASP.NET application use SSL? I've written an e-commerce application and want to make just the checkout page use SSL for secure transmission. ...
2
by: Keith Patrick | last post by:
I have a web app that consists of a single page. It works a lot like starter kit examples of menu/content apps, and it has a sitemap associated with it. However, my app doesn't go from page to...
3
by: arteezan | last post by:
Mabuhay! I'm new in PHP and i want to create a single PHP page where the links are linked to contents within that single page. can anyone please help me with this? thanks in advance to anyone who...
3
by: google | last post by:
Hi I'm looking for some advice, so if anyone wants to contribute I would be grateful. I'm trying to create a web application. By application I mean something that is like a Windows...
1
by: Andrew Burton | last post by:
I'm poking at a small "single page application" (SPA), ala TiddlyWiki, to act as kind of a local, single-user version of Twitter (no real application, except to familiarize myself with JavaScript)....
2
by: =?Utf-8?B?RGFu?= | last post by:
is anyone know why and how to overcome this problem discussed on this thread. http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1984652&SiteID=1
1
by: timsamshuijzen | last post by:
The website I am developing is implemented as a Single Page Interface (SPI). During a visitor's session all new content gets loaded by JavaScript (Ajax), no new pages get loaded and the URL in the...
3
NawazAhmed
by: NawazAhmed | last post by:
Hi, I know this is a very simple question....But I tried every possible way I know to answer this question and failed everytime. This is the scenario: I am using Visual Studio 2008 and Sql 2005....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.