Dmitry Kazakov Dmitry Kazakov - 1 year ago 64
C# Question

How to listen socket in single ASP.NET 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.NET page closed (by user) to disconnect from server?

Server Console App:

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.NET client side:

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
setInterval("__doPostBack('upDynamicClock', '');", 1000);
to refresh page

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download