惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
AWS News Blog
AWS News Blog
V
Vulnerabilities – Threatpost
D
Darknet – Hacking Tools, Hacker News & Cyber Security
量子位
博客园 - 叶小钗
AI
AI
T
Tor Project blog
Forbes - Security
Forbes - Security
W
WeLiveSecurity
博客园_首页
爱范儿
爱范儿
J
Java Code Geeks
B
Blog
G
GRAHAM CLULEY
aimingoo的专栏
aimingoo的专栏
Cloudbric
Cloudbric
C
CXSECURITY Database RSS Feed - CXSecurity.com
TaoSecurity Blog
TaoSecurity Blog
L
LINUX DO - 热门话题
阮一峰的网络日志
阮一峰的网络日志
有赞技术团队
有赞技术团队
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Simon Willison's Weblog
Simon Willison's Weblog
云风的 BLOG
云风的 BLOG
Google DeepMind News
Google DeepMind News
H
Help Net Security
博客园 - 三生石上(FineUI控件)
C
Cisco Blogs
C
Cybersecurity and Infrastructure Security Agency CISA
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
P
Palo Alto Networks Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recent Commits to openclaw:main
Recent Commits to openclaw:main
博客园 - 司徒正美
The Last Watchdog
The Last Watchdog
Blog — PlanetScale
Blog — PlanetScale
T
The Blog of Author Tim Ferriss
S
Secure Thoughts
Spread Privacy
Spread Privacy
F
Fortinet All Blogs
月光博客
月光博客
大猫的无限游戏
大猫的无限游戏
S
SegmentFault 最新的问题
H
Hackread – Cybersecurity News, Data Breaches, AI and More
A
About on SuperTechFans
Security Latest
Security Latest
Webroot Blog
Webroot Blog
Scott Helme
Scott Helme
Hugging Face - Blog
Hugging Face - Blog

博客园 - FredGrit

WPF TreeView show WCF config file WPF itemscontrol loaded downloaded data from WCF via httpclient WPF TreeView HierarchicalDataTemplate DataTemplate, Enum get enum name WPF consume xml generated by WCF , C# deserialize xml to List WPF implemented ICommand and IDisposable WPF ContextMenu,MenuItem command can binding to datacontext's command directly WPF usercontrol pass contextmenu command via implemented Freezable class which does not attach on Visual tree, then invoked in caller MVVM WPF consume data generate by WCF and save via ContextMenu Command in MVVM C# export List<T> to excel file via EPPlus WPF ContextMenu does not rely on host visual tree, the Freezable can exist independently, convey dependency property in usercontrol to caller C# JsonConvert DeserializeObject MissingMemberHandling.Ignore when the source model is completed and the required is partial Freezable objects do not require attachment to the WPF visual tree, maintain a persistent lifetime, and serve as a reliable binding relay between a detached ContextMenu and its parent host control. C# run httplistener to act as service application asynchronously in console, semaphoreslim allow the max concurrent number WPF Microsoft.Xaml.Behaviors.WPF, EventTrigger EventName="PreviewMouseDown" the tunnel event, while the MouseDown can't trigger the command because it was swallowed WPF customize command implemented ICommand, volatile read method is thread safe, preventing cpu and comipler reorder and optimization. WPF ItemsControl load huge 50M+ data WPF consume data generated by WCF periodically in json format WPF customize command based on ICommand and manually trigger WPF consume data generated by grpc services C# produce and consume data via Google.Protobuf WCF produce message and WPF consume periodically via DispatcherTimer WCF deconstruct WebConfig includes bindings, behaviors, service, endpoint ,serviceHostingEnvironment C# insert data into SQLite in batch periodically WPF SQLite SQLiteStudio WPF customize MultiSelectComboBox based on combobox WPF DataGrid Context menu binding command and commandparameter to datacontext WCF set fixed port as http://localhost:8888/ via Project /Properties/web/project url to create virtual directory WPF customize datagrid behavior based on behavior&lt;datagrid&gt; with command and command parameter WPF Microsoft Visual Studio XAML designer is busy WCF WebHttpBinding support both http and https WCF support basicHttpBinding and webHttpBinding - FredGrit WCF TestClient set fixed configuration file WPF consume http json and update periodically via DispatcherTimer WPF Prism.Core version 9.0.537 implemented navigation register singleton with splash screen, pass global variable via RegisterSingleton method WPF render periodically via DispatcherTimer, customize behavior - FredGrit Python cosume WCF service via requests in json format WPF call webHttpBinding from WCF WCF binding webHttpBinding is used to web browser in json format both in request and response WPF invoke WCF dll periodically via DispatcherTimer WCF webHttpBinding is open for web browser and wpf WPF DataTemplateSelector WPF DataGrid customize behavior with multiple commands and command parameters then invoke in mvvm WPF DataGrid behavior customize command and command parameter then invoke and implemented in MVVM WPF ItemsControl customize behavior and save all items WCF service can be accessed by browser WPF WCF produce data as service and WPF consume data as client periodically WPF GRPC and Probuf generated data as service then consume by wpf periodically WPF customize behavior based on Microsoft.Xaml.Behaviors.Wpf with command and commandparameter WPF call data from CPP wrapper dll via CLI\CLR - FredGrit WPF customize behavior WPF get gpu information via System.Management WPF ItemsControl IsItemsHost=True WPF Customize behavior and dependency property command C# Serilog, Serilog.Sinks.Console, Serilog.Sinks.File C# Serilog both in file and console Windows powershell view huge file via command C# serialize huge data more than 100M via splitting into batch and concatenating as one big json file WPF WeakReference C# serialize datetime then deserialize, print lose precision. resolve by ToString(&quot;o&quot;) C# write generated data service and sent via websocket, then consume by python periodically C# DateTime print precision to microseconds C# WebSocket console as service provide data, another console as client,send request periodically C# WebAPI [HttpGet(&quot;{cnt}&quot;] pass argument WPF implement ICommand with async execute WPF ListBox control virtualization in mvvm WPF Data Source invoke from web api C# WebAPI
C# produce data and send via WebSocket as service, Python,Flask,HTML as consumer invoke periodically
FredGrit · 2026-03-19 · via 博客园 - FredGrit
//C# Server
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;

namespace ConsoleApp7
{
    public class Program
    {
        static async Task Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            var listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:5000/ws/");
            listener.Start();

            Console.WriteLine($"{DateTime.Now},WebSocket Server started at ws://localhost:5000/ws/");
            while (true)
            {
                var context = await listener.GetContextAsync();

                if (context.Request.IsWebSocketRequest)
                {
                    _ = HandleClient(context);
                }
                else
                {
                    context.Response.StatusCode = 400;
                    context.Response.Close();
                }
            }
        }

        static async Task HandleClient(HttpListenerContext context)
        {
            var wsContext = await context.AcceptWebSocketAsync(null);
            var socket = wsContext.WebSocket;

            Console.WriteLine($"{DateTime.Now},Client connected");

            var buffer = new byte[1024];

            while (socket.State == WebSocketState.Open)
            {
                var result = await socket.ReceiveAsync(buffer, CancellationToken.None);

                if (result.MessageType == WebSocketMessageType.Close)
                {
                    await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
                    break;
                }

                var request = Encoding.UTF8.GetString(buffer, 0, result.Count);
                //Console.WriteLine($"Received: {request}");

                var bksList = GetBooksList();

                var json = JsonSerializer.Serialize(bksList);
                var bytes = Encoding.UTF8.GetBytes(json);

                await socket.SendAsync(bytes, WebSocketMessageType.Text, true, CancellationToken.None);

                var ids = bksList.Select(x => x.Id);
                string msg = $"MinId:{ids.Min()},MaxId:{ids.Max()}";
                Console.WriteLine($"{DateTime.Now.ToString("yyyyMMddHHmmssffff")} sent data,{msg}");
            }
        }

        static int idx = 0;
        static int GetIdx()
        {
            return Interlocked.Increment(ref idx);
        }

        static List<Book> GetBooksList()
        {
            List<Book> bksList = new List<Book>();
            for (int i = 0; i < 1000; i++)
            {
                var a = GetIdx();
                bksList.Add(new Book()
                {
                    Id = a,
                    Name = $"Name_{a}",
                    Author = $"Author_{a}",
                    ISBN = $"ISBN_{a}_{Guid.NewGuid():N}",
                    Comment = $"Comment_{a}",
                    Content = $"Content_{a}",
                    Summary = $"Summary_{a}",
                    Title = $"Title_{a}",
                    Topic = $"Topic_{a}"
                });
            }
            return bksList;
        }
    }

    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ISBN { get; set; }
        public string Author { get; set; }
        public string Comment { get; set; }
        public string Content { get; set; }
        public string Summary { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
    }
}
//Client
//app.py
import asyncio
import json
from flask import Flask, render_template, jsonify
import websockets
from datetime import datetime

app = Flask(__name__)

WS_URL = "ws://localhost:5000/ws/"

async def fetch_ws_data():
    async with websockets.connect(WS_URL, max_size=None) as ws:
        await ws.send("get_data")
        message = await ws.recv()
        data_list = json.loads(message)
        print(f'{datetime.now().strftime('%y%m%d%H%M%S%f')},len:{len(data_list)}')
        return data_list

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/data")
def get_data():
    data = asyncio.run(fetch_ws_data())
    return jsonify(data)

if __name__ == "__main__":
    app.run(debug=True,port=5001)

//templates/index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Book Data</title>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <style>
        table {
            border-collapse: collapse;
            width: 100%;
        }
        th, td {
            border: 1px solid #ccc;
            padding: 6px;
            font-size: 12px;
        }
        th {
            background: #f5f5f5;
        }
        .pager {
            margin-top: 10px;
        }
        .time-display {
            position: absolute;
            top: 10px;
            right: 10px;
            font-size: 25px;
            color: #333;
            font-weight: bold;
        }
    </style>
</head>

<body>
<div class="time-display" id="currentTime"></div>

<h2>Book List(Refresh every 10 seconds)</h2>

<table id="tbl">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Author</th>
            <th>ISBN</th>
            <th>Comment</th>
            <th>Content</th>
            <th>Summary</th>
            <th>Title</th>
            <th>Topic</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

<div class="pager">
    <button id="prev">Prev</button>
    <span id="pageInfo"></span>
    <button id="next">Next</button>
</div>

<script>
    let allData = [];
    let pageSize = 30;
    let currentPage = 1;

    function loadData() {
        $.get("/data", function (res) {
            allData = res;
            currentPage = 1;
            render();
        });
    }

    function render() {
        let start = (currentPage - 1) * pageSize;
        let end = start + pageSize;

        let pageData = allData.slice(start, end);

        let html = "";
        pageData.forEach(x => {
            html += `<tr>
                <td>${x.Id}</td>
                <td>${x.Name}</td>
                <td>${x.Author}</td>
                <td>${x.ISBN}</td>
                <td>${x.Comment}</td>
                <td>${x.Content}</td>
                <td>${x.Summary}</td>
                <td>${x.Title}</td>
                <td>${x.Topic}</td>
            </tr>`;
        });

        $("#tbl tbody").html(html);

        let totalPage = Math.ceil(allData.length / pageSize);
        $("#pageInfo").text(`Page ${currentPage} / ${totalPage}`);
    }

    $("#prev").click(function () {
        if (currentPage > 1) {
            currentPage--;
            render();
        }
    });

    $("#next").click(function () {
        let totalPage = Math.ceil(allData.length / pageSize);
        if (currentPage < totalPage) {
            currentPage++;
            render();
        }
    });
  
    setInterval(loadData, 10000);
  
    loadData();
 
    function updateTime() {
        const now = new Date(); 
        const formattedTime = now.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
        }).replace(/\//g, '-');
        $("#currentTime").text(formattedTime);
    } 
    updateTime(); 
    setInterval(updateTime, 1000);
</script>

</body>
</html>
PS D:\PY\WSPython>  d:; cd 'd:\PY\WSPython'; & 'c:\Users\fred\AppData\Local\Programs\Python\Python314\python.exe' 'c:\Users\fred\.vscode\extensions\ms-python.debugpy-2025.18.0-win32-x64\bundled\libs\debugpy\launcher' '64256' '--' 'D:\PY\WSPython\app.py' 
 * Serving Flask app 'app'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5001
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 171-430-863
127.0.0.1 - - [18/Mar/2026 23:56:18] "GET / HTTP/1.1" 200 -
260318235619123576,len:1000
127.0.0.1 - - [18/Mar/2026 23:56:19] "GET /data HTTP/1.1" 200 -
260318235629843525,len:1000
127.0.0.1 - - [18/Mar/2026 23:56:29] "GET /data HTTP/1.1" 200 -
260318235639827851,len:1000
127.0.0.1 - - [18/Mar/2026 23:56:39] "GET /data HTTP/1.1" 200 -
260318235649846548,len:1000
127.0.0.1 - - [18/Mar/2026 23:56:49] "GET /data HTTP/1.1" 200 -
260318235659834247,len:1000
127.0.0.1 - - [18/Mar/2026 23:56:59] "GET /data HTTP/1.1" 200 -
260318235709838274,len:1000
127.0.0.1 - - [18/Mar/2026 23:57:09] "GET /data HTTP/1.1" 200 -
260318235719832258,len:1000
127.0.0.1 - - [18/Mar/2026 23:57:19] "GET /data HTTP/1.1" 200 -
260318235732831504,len:1000
127.0.0.1 - - [18/Mar/2026 23:57:32] "GET /data HTTP/1.1" 200 -
260318235832854250,len:1000
127.0.0.1 - - [18/Mar/2026 23:58:32] "GET /data HTTP/1.1" 200 -

image

image