目录

介绍

为什么我们使用Node.js?

使用代码

测试和运行

参考


  • 通过WCF应用程序下载Node.js - 8.8 MB

介绍

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

为什么我们使用Node.js?

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

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

在某些情况下我们需要继续使用.net平台并只使用来自node.js的好处。在这种情况下,我已经借助WCF编写了这段代码,以便与MS Sql Server进行通信,而不是安装诸如node-ts,node-sqlserver,mssqlhelper,mssqlx,edge.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 Clientsocket.emit('message', { 'message': 'Hello this message is from Server' });//Receive Data From Clientsocket.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 verburl: "http://localhost:28448/MyService.svc/GetCustomer", // Location // of the service//data: Data,                            //Data sent to servercontentType: "application/json; charset=utf-8", // content type sent to serverdataType: "text",                        //Expected data format from serverprocessdata: true,                       //True or Falsesuccess: function (msg) {                //On Successful service callvar 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

.Net开发人员通过WCF使用Node.js相关推荐

  1. gwt-2.8.2下载_从GWT开发人员的角度概述Scala.js

    gwt-2.8.2下载 该博客严重偏向于GWT(和基于GWT的框架),但是我谨记,将来GWT可能会被其他技术取代,因此我们始终愿意探索其他平台/框架. 正如他们所说,多元化可以降低风险. 每种编程语言 ...

  2. 从GWT开发人员的角度概述Scala.js

    该博客严重偏向于GWT(和基于GWT的框架),但是我们牢记未来GWT可能会被其他技术所取代,因此我们始终愿意探索其他平台/框架. 正如他们所说,多元化可以降低风险. 每种编程语言,甚至最奇怪的编程语言 ...

  3. node mysql商城开发_NideShop:基于Node.js+MySQL开发的微信小程序商城开源啦

    NideShop:基于Node.js+MySQL开发的微信小程序商城开源啦 发布时间:2020-04-14 04:23:37 来源:51CTO 阅读:2894 作者:ch10mmt 高仿网易严选的微信 ...

  4. java开发小菜鸟初遇前端node.js

    这就是有的时候我们要设置path路径,有的时候使用编译环境之后就不需要再设置path环境变量的原因: cmd :命令窗口 终端 dir 列出当前目录下的文件 cd 进入到指定的文件 md 创建文件夹 ...

  5. 善于使用F12开发人员工具来快速调试js代码

    使用F12工具快速调试扣出的js代码 前言 该文章讲述,如何善于使用F12开发人员工具来高效的调试代码,这里以360极速浏览器为案例,并且推荐使用这款浏览器,非常高效. 一.打开浏览器,打开F12开发 ...

  6. nvm install node没反应_前端开发,你要懂得Node.js的安装和使用方法

  7. 2021年Node.js开发人员学习路线图

    Node.js 自发布以来,已成为业界重要破局者之一.Uber.Medium.PayPal 和沃尔玛等大型企业,纷纷将技术栈转向 Node.js.Node.js 支持开发功能强大的应用,例如实时追踪 ...

  8. 2021 年 Node.js 开发人员学习路线图

    前言:总有小伙伴问 Node.js 如何深入学习,本文是一个不错的学习大纲. Node.js 自发布以来,已成为业界重要破局者之一.Uber.Medium.PayPal 和沃尔玛等大型企业,纷纷将技术 ...

  9. aws mongodb_使用Node.js,AWS Lambda和MongoDB Atlas进行无服务器开发

    aws mongodb This article was originally published on mongoDB. Thank you for supporting the partners ...

最新文章

  1. NLP 新宠:谈Prompt的前世今生
  2. org.apache.struts2.dispatcher.FilterDispatcher的四个功能
  3. 微服务发现组件Eureka:微服务注册
  4. CodeForces - 1332B Composite Coloring(数论+构造)
  5. 二:Maven中pom.xml元素详解
  6. win7桌面计算机没了,win7系统桌面的计算机图标没了的解决方法
  7. C++控制台打飞机小游戏 | CSDN 博文精选
  8. 使用 ssh-copy-id 配置 ssh免密登录
  9. 《零基础学习Liunx之三》 The following takes place between 04:00PM and 05:00PM
  10. java学习之单件模式
  11. openCV银行卡号识别
  12. 《动手学深度学习》(PyTorch版)代码注释 - 52 【World2Vec_Learning】
  13. 使用mysql workbench显示Tables/Views could not be fetched
  14. 如何看待国企纷纷卸载微软Office改用金山WPS?
  15. 进制转换 2进制转10进制 10进制转2进制
  16. 移动硬盘插到电脑上突然打不开或者没有显示的解决方法【已解决】不删设备不删驱动不改电源选项
  17. 什么是BFC?BFC的形成条件?BFC的应用场景
  18. java 外卖_java实现外卖订餐系统
  19. 魔兽模型路径查看更改工具
  20. R语言从入门到精通Day1之【R语言介绍】

热门文章

  1. python和c 先学哪个-C和Python我该先学什么?
  2. 元宵节电商促销活动首页PSD分层模板
  3. UI设计灵感|如果你想设计一款有趣的状态提示,看这里OOPS!
  4. 手机海报模板,收藏就对了!
  5. UI设计素材帮手, 排版技巧设计师
  6. mysql 流量带宽_流量与带宽
  7. arduino灯光装置_【pinpong库控制硬件】之Arduino uno-调光台灯
  8. Python--爬虫初学(11.5)
  9. cuSPARSE库:(一)函数的异步执行
  10. 实时Linux内核调度器 | Real-Time Linux Kernel Scheduler