如何在单个ASP.NET页面中监听套接字

时间:2014-02-19 03:59:25

标签: c# sockets tcp

我正在使用TCP Socekts和C#开发客户端 - 服务器应用程序。我需要从控制台应用程序发送消息到ASP页面。我可以使用OnLoad事件从ASP页面连接,有时在PageLoad事件上我只能收到几条消息。我有两个问题: 1.如何连续监听服务器套接字并接收消息? 2.如何知道ASP.NET页面何时关闭(由用户)与服务器断开连接?

服务器控制台应用:

        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客户端:

    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正在发送到WinApp和ConsoleApp而没有任何问题。但是使用ASP页面,我只能正确接收Connect消息,有时我只能收到1-2-3 msg。我使用javascript setInterval("__doPostBack('upDynamicClock', '');", 1000);刷新页面

1 个答案:

答案 0 :(得分:1)

HTTP是无状态的,ASP.NET WebForms只试图用viewstate等隐藏它。只要您在浏览器中看到该页面,该页面就不再存在,您的OnSend回调将不再被调用。这也在Create web page with live socket based data中解释。

如果您的目标是使用服务器提供的数据更新HTML元素,请查看SignalR

相关问题