【问题标题】:ASP.NET C# WebSocketASP.NET C# WebSocket
【发布时间】:2016-11-14 02:01:59
【问题描述】:

我创建了一个 ASP.NET C# 项目,它由一个 Web 表单和一个 WebSocket 处理程序组成。我想以 JSON 字符串格式将 2 个数据(名称和价格数据)从 Web 表单发送到 WebSocket 处理程序。这是网页表单中的代码sn-p:

            ws.onopen = function()
           {

               var name = "Client Product";
               var price = 10.8;
               ws.send(JSON.stringify(name));
               ws.send(JSON.stringify(price));
              alert("Message is sent...");
           };

在 WebSocket 处理程序的 OnMessage(string) 方法中,我想检索 web 表单发送的 2 个数据并将这 2 个数据反序列化为 c# 格式。这是 WebSocket 处理程序中的代码 sn-p:

     public override void OnMessage(string message)
    {
        string serverName="";
        string serverPrice = "";

        serverName = JsonConvert.DeserializeObject<string>(message);
        serverPrice = JsonConvert.DeserializeObject<string>(message);

    }

但是,在 WebSocket 处理程序的 onMessage(string) 方法下,变量 serverName 和 serverPrice 都将被分配为“客户端产品”。我希望将变量 serverPrice 分配为“10.8”,而不是“客户端产品”。

有人可以告诉我如何实现这一目标吗?如果您能帮助我,我将不胜感激:)谢谢:)

【问题讨论】:

    标签: c# asp.net json websocket json.net


    【解决方案1】:

    如果您想在单个 JSON 消息中发送多条数据,您需要将它们组合成一个对象。试试这样:

    在客户端:

    ws.onopen = function()
    {
        var obj = {
            name: "Client Product",
            price: "10.8"
        };
        ws.send(JSON.stringify(obj));
        alert("Message is sent...");
    };
    

    在服务器上:

    public override void OnMessage(string message)
    {
        MyData obj = JsonConvert.DeserializeObject<MyData>(message);
    
        string serverName = obj.Name;
        string serverPrice = obj.Price;
    
        ...
    }
    
    public class MyData
    {
        // Important: these JsonProperty attributes MUST match
        // the names of the properties in the client object
    
        [JsonProperty("name")]
        public string Name { get; set; }
    
        [JsonProperty("price")]
        public string Price { get; set; }
    }
    

    【讨论】:

    • 非常感谢,Brian :) 你救了我的命 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多