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

标签 c# sockets tcp

我正在使用 TCP Socekts 和 C# 开发客户端-服务器应用程序。我需要将消息从控制台应用程序发送到 ASP 页面。我可以使用 OnLoad 事件从 ASP 页面进行连接,有时在 PageLoad 事件中我只能收到几条消息。我有两个问题: 1、如何持续监听服务器socket并接收消息?
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);
    }
}

服务器应用程序正在毫无问题地发送到 WinApp 和 ConsoleApp。但是对于 ASP 页面,我只能正确接收连接消息,有时我只能接收 1-2-3 消息。我正在使用 javascript setInterval("__doPostBack('upDynamicClock', '');", 1000); 来刷新页面

最佳答案

HTTP 是无状态的,ASP.NET WebForms 仅尝试使用 View 状态等隐藏它。一旦您在浏览器中看到该页面,该页面就不再存在,您的 OnSend 回调将不再被调用。这也在 Create web page with live socket based data 中进行了解释。 .

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

关于c# - 如何在单个 ASP.NET 页面中监听套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21870740/

相关文章:

c# - 如何判断tcp是否连接?

c# - 如何从字典 C# 返回 tvalues

C# System.Diagnostics.Process.Start() 参数

tcp - ZOS上连接PID和端口

java - Tomcat 处理时间很小但 nginx 显示它很大

Android:OutputStreamWriter 刷新后未发送数据(套接字)

c# - C#中相同数组的不同哈希码

c# - 如何获取 SharePoint 中所有用户的列表

c - Linux - 串口行为不同于套接字

c - open命令适合二进制文件操作吗