.Net开发人员通过WCF使用Node.js

635 篇文章 16 订阅
236 篇文章 4 订阅

目录

介绍

为什么我们使用Node.js?

使用代码

测试和运行

参考


介绍

如今,在各种领域中都需要将实时Web应用程序作为双向连接。Javascript是一个很好的解决方案,但它只是在客户端工作,而有一些场景,我们真的需要有在服务器端工作的解决方案。例如,在数据库中存储数据或在服务器端处理数据。有两种流行的技术,一种是SignalR 和另一种是Node.js.

为什么我们使用Node.js

首先,对大多数人来说,这是因为我们需要一个双向的Web应用程序的实时解决方案,从客户端到服务器,从服务器到客户端,这样数据就可以在双方之间共享。Node.js的另一个优点是它是跨平台的,使用前不需要复杂的准备和安装。它很好地建立了I/O,最后但并非最不重要的是,数据丢失的可能性太少了。

 虽然Node.js的体系结构如下图所示,用于在客户端和服务器之间流动数据。但通过使用我所描述的一些解决方案,可以与数据库建立连接:

在某些情况下我们需要继续使用.net平台并只使用来自node.js的好处。在这种情况下,我已经借助WCF编写了这段代码,以便与MS Sql Server进行通信,而不是安装诸如node-tsnode-sqlservermssqlhelpermssqlxedge.js之类的驱动程序。

使用代码

1.文件 - >新建项目 - > WebApplication

2.解决方案 - >右键单击 - >添加新项目 - >类库 - > DAL

3.添加New Item-> Class - > DataAccess.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.Common;

namespace DAL
{
    public abstract class DataAccess
    {
        public string ConnectionString
        {
            get
            {
                return "Data Source =DESKTOP-EVM02NE\\MAHSA; 
                Initial Catalog = NodeByWCF; Integrated Security=true ";
                //return ConfigurationSettings.AppSettings["ConnectionString"].ToString();
            }
        }

        protected Int32 ExecuteNonQuery(DbCommand cmd)
        {
            return cmd.ExecuteNonQuery();
        }

        protected IDataReader ExecuteReader(DbCommand cmd)
        {
            return ExecuteReader(cmd, CommandBehavior.Default);
        }

        protected IDataReader ExecuteReader(DbCommand cmd, CommandBehavior behavior)
        {
            return cmd.ExecuteReader(behavior);
        }

        protected object ExecuteScalar(DbCommand cmd)
        {
            return cmd.ExecuteScalar();
        }
    }
}

4.添加New Item-> Class - > CustomerDAL.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
   public class CustomerDAL : DataAccess
    {
        public CustomerDAL()
        {

        }
        public IEnumerable<customer> Load()
        {
            SqlConnection conn = new SqlConnection(ConnectionString);
            SqlDataAdapter dAd = new SqlDataAdapter("select * from Customer", conn);
            dAd.SelectCommand.CommandType = CommandType.Text;
            DataTable dt = new DataTable();
            try
            {
                dAd.Fill(dt);

                foreach (DataRow row in dt.Rows)
                {
                    yield return new Customer
                    {
                        ID = Convert.ToInt32(row["ID"]),
                        Name = (row["Name"]).ToString()
                    };
                }
            }

            finally
            {                
                dAd.Dispose();
                conn.Close();
                conn.Dispose();
            }
        }
    }
}

5.添加New Item - > Class - > Customer.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class Customer
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
}

6.解决方案 - >右键单击 - >添加新项目 - >类库 - > BAL

7.添加New Item-> Class - > CustomerBAL.cs

using DAL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BAL
{
    public class CustomerBAL
    {
        public IEnumerable<dal.customer> Load()
        {
            CustomerDAL customer = new CustomerDAL();
            try
            {               
                return customer.Load();
            }

            catch
            {
                throw;
            }
            finally
            {
                customer = null;
            }
        }
    }
}

8.解决方案 - >右键单击 - >添加新项目 - > WebApplication

9.添加New Item-> WCF Service(启用Ajax - > MyService.svc

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using BAL;
using DAL;
using System.Web.Script.Serialization;

namespace WebApplication
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = 
                                     AspNetCompatibilityRequirementsMode.Allowed)]
    public class MyService
    { 
        [OperationContract]
        [WebGet()]
        public string GetCustomer()
        {
            CustomerBAL  _Cust = new CustomerBAL();
            try
            {
                var customers = _Cust.Load();
                string json = new JavaScriptSerializer().Serialize(customers);


                return json;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
               
            }
        }      
    }
}

10.解决方案 - >右键单击 - >添加新项目 - > Javascript - >空白Node.js Web应用程序

11. Server.js

var http = require("http");
var url = require('url');
var fs = require('fs');
var io = require('socket.io');
var port = process.env.port || 1337;

var server = http.createServer(function (request, response) {
    var path = url.parse(request.url).pathname;
    
    switch (path) {
        case '/':
            response.writeHead(200, { 'Content-Type': 'text/html' });
            response.write('hello world');
            response.end();
            break;
        case '/Index.html':
            fs.readFile(__dirname + path, function (error, data) {
                if (error) {
                    response.writeHead(404);
                    response.write("page doesn't exist - 404");
                    response.end();
                }
                else {
                    response.writeHead(200, { "Content-Type": "text/html" });
                    response.write(data, "utf8");
                    response.end();
                }
            });
            break;
        default:
            response.writeHead(404);
            response.write("page this doesn't exist - 404");
            response.end();
            break;
    }
});

server.listen(port);

var listener = io.listen(server);
listener.sockets.on('connection', function (socket) {
    //Send Data From Server To Client
    socket.emit('message', { 'message': 'Hello this message is from Server' });
    
    //Receive Data From Client
    socket.on('client_data', function (data) {
        
        socket.emit('message', { 'message': data.name });
        socket.broadcast.emit('message', { 'message': data.name });
        
        process.stdout.write(data.name);
        console.log(data.name);
    });
});

12. Index.html   

<input id="text" type="text" /><button id="send">send</button>

 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>

    <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
    <script src="http://localhost:8080/server.js"></script>
    <script src="/server.js"></script>
    <script>
        var socket = io.connect();

        socket.on('message', function (data) {
            $('#conversation').append('
' + data.message);
        });

        $(document).ready(function () {
            $('#send').click(function () {

                $.ajax({
                    type: "GET", //GET or POST or PUT or DELETE verb
                    url: "http://localhost:28448/MyService.svc/GetCustomer", // Location 
                                                             // of the service
                    //data: Data,                            //Data sent to server
                    contentType: "application/json; charset=utf-8", // content type sent to server
                    dataType: "text",                        //Expected data format from server
                    processdata: true,                       //True or False
                    success: function (msg) {                //On Successful service call
                        var obj = JSON.parse(msg);
                        var t = obj.d.length;

                        var completeMsg = "";
                        for (var i = 0; i < t; i++) {
                            completeMsg = completeMsg + "  " + obj.d[i].Name;
                        }
                        alert(completeMsg);
                        socket.emit('client_data', { 'name': completeMsg });
                    }
                });
            })
        });
    </script>

测试和运行

键入:Localhost:1337/Index.html

点击发送按钮数据将来自Node.js上的数据库

参考

http://www.codeproject.com/Articles/132809/Calling-WCF-Services-using-jQuery

http://www.infragistics.com/community/blogs/mihail_mateev/archive/2014/07/18/dealing-with-node-js-and-microsoft-sql-server-part-1.aspx

 

原文地址: https://www.codeproject.com/Articles/1111793/Node-js-For-Net-Developers-By-WCF

***pm,你可以尝试以下几个步骤来解决问题: 1. 检查npm的配置:首先,你需要确认你的npm配置正确。你可以使用命令npm config get registry来检查当前的registry配置。如果返回https://registry.npmjs.org/,则说明npm的registry配置正确。 2. 检查网络连接:确保你的电脑能够正常连接到互联网,有时候网络问题可能导致npm无法安装cnpm。 3. 更换registry源:如果你仍然无法安装cnpm,你可以尝试更换registry源为淘宝的源。你可以使用命令npm config set registry http://registry.npm.taobao.org/来将registry源更换成淘宝的源。然后再次尝试安装cnpm。 4. 重新安装npm和node.js:如果以上方法都不起作用,你可以尝试卸载并重新安装npm和node.js。首先,你需要卸载已有的npm和node.js,然后重新下载并安装最新版本的npm和node.js。 希望以上方法能够帮助你解决npm装不了cnpm的问题。如果问题仍然存在,请提供更多的细节,以便我能够给出更准确的解决方案。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [npm换成cnpm的方法](https://blog.csdn.net/wcf2010/article/details/115360263)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [windows实现npm和cnpm安装步骤](https://download.csdn.net/download/weixin_38745434/12933534)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值