什么样拔取HTML5的WebSocket完结网页与服务器的双工通信(二)

by admin on 2019年2月11日

本体系服务端双工通讯包涵二种落成格局:一、使用Socket打造;二、使用WCF创设。本文为使用WCF打造服务端的双工通讯,客户端同样应用Html5的WebSocket技术拓展调用。

本种类服务端双工通讯包罗三种已毕方式:一、使用Socket营造;二、使用WCF构建。本文为利用WCF创设服务端的双工通讯,客户端同样选用Html5的WebSocket技术拓展调用。

一、创建WCF服务库Wcf.Duplex.Library:

一、创建WCF服务库Wcf.Duplex.Library:

1.定义协议的劳务接口:

1.概念协议的劳动接口:

亚洲必赢手机 1亚洲必赢手机 2

亚洲必赢手机 3亚洲必赢手机 4

 1 [ServiceContract]
 2 public interface IWebSocketEchoCallback
 3 {
 4 [OperationContract(IsOneWay = true, Action = "*")]
 5 void Send(Message message);
 6 }
 7 
 8 [ServiceContract(CallbackContract = typeof(IWebSocketEchoCallback))]
 9 public interface IWebSocketEcho
10 {
11 [OperationContract(IsOneWay = true, Action = "*")]
12 void Receive(Message message);
13 }
 1 [ServiceContract]
 2 public interface IWebSocketEchoCallback
 3 {
 4 [OperationContract(IsOneWay = true, Action = "*")]
 5 void Send(Message message);
 6 }
 7 
 8 [ServiceContract(CallbackContract = typeof(IWebSocketEchoCallback))]
 9 public interface IWebSocketEcho
10 {
11 [OperationContract(IsOneWay = true, Action = "*")]
12 void Receive(Message message);
13 }

View Code

View Code

注意:

注意:

OperationContract中的Action,一定要安装。

OperationContract中的Action,一定要安装。

IWebSocketEcho接口中:只好定义一个OperationContract(IsOneWay = true,
Action = “*”)方法入口,否则使用WebSocket连接时会报错

亚洲必赢手机,IWebSocketEcho接口中:只可以定义一个OperationContract(IsOneWay = true,
Action = “*”)方法入口,否则使用WebSocket连接时会报错

IWebSocketEchoCallback
回调接口中:可以定义七个OperationContract(IsOneWay = true, Action =
“*”)方法

IWebSocketEchoCallback
回调接口中:可以定义八个OperationContract(IsOneWay = true, Action =
“*”)方法

2.落到实处劳务协议,并定义一个时钟,定时调用回调方法,发送新闻给客户端:

2.落到实处劳务协议,并定义一个时钟,定时调用回调方法,发送消息给客户端:

亚洲必赢手机 5亚洲必赢手机 6

亚洲必赢手机 7亚洲必赢手机 8

 1 public class EchoService : IWebSocketEcho
 2 {
 3 
 4 IWebSocketEchoCallback _callback = null;
 5 
 6 public EchoService()
 7 {
 8 
 9 //获取回调信道
10 _callback =
11 OperationContext.Current.GetCallbackChannel<IWebSocketEchoCallback>();
12 
13 Timer time = new Timer(10000);
14 time.Elapsed += time_Elapsed;
15 time.Start();
16 }
17 void time_Elapsed(object sender, ElapsedEventArgs e)
18 {
19 _callback.Send(CreateMessage("Message From WebSockets Host" + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
20 }
21 public void Receive(Message message)
22 {
23 if (message == null)
24 {
25 throw new ArgumentNullException("message");
26 }
27 
28 WebSocketMessageProperty property =
29 (WebSocketMessageProperty)message.Properties["WebSocketMessageProperty"];
30 WebSocketContext context = property.WebSocketContext;
31 var queryParameters = HttpUtility.ParseQueryString(context.RequestUri.Query);
32 string content = string.Empty;
33 
34 if (!message.IsEmpty)
35 {
36 byte[] body = message.GetBody<byte[]>();
37 content = Encoding.UTF8.GetString(body);
38 }
39 
40 // Do something with the content/queryParams
41 // ...
42 
43 string str = null;
44 if (string.IsNullOrEmpty(content)) // Connection open message
45 {
46 str = "Opening connection from user " +
47 queryParameters["Name"].ToString();
48 }
49 else // Message received from client
50 {
51 str = "Received message: " + content;
52 }
53 wcf.websocket.forweb.LogHelper.log.Error(str);
54 _callback.Send(CreateMessage(str));
55 }
56 
57 private Message CreateMessage(string content)
58 {
59 Message message = ByteStreamMessage.CreateMessage(
60 new ArraySegment<byte>(
61 Encoding.UTF8.GetBytes(content)));
62 message.Properties["WebSocketMessageProperty"] =
63 new WebSocketMessageProperty { MessageType = WebSocketMessageType.Text };
64 
65 return message;
66 }
67 }
 1 public class EchoService : IWebSocketEcho
 2 {
 3 
 4 IWebSocketEchoCallback _callback = null;
 5 
 6 public EchoService()
 7 {
 8 
 9 //获取回调信道
10 _callback =
11 OperationContext.Current.GetCallbackChannel<IWebSocketEchoCallback>();
12 
13 Timer time = new Timer(10000);
14 time.Elapsed += time_Elapsed;
15 time.Start();
16 }
17 void time_Elapsed(object sender, ElapsedEventArgs e)
18 {
19 _callback.Send(CreateMessage("Message From WebSockets Host" + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
20 }
21 public void Receive(Message message)
22 {
23 if (message == null)
24 {
25 throw new ArgumentNullException("message");
26 }
27 
28 WebSocketMessageProperty property =
29 (WebSocketMessageProperty)message.Properties["WebSocketMessageProperty"];
30 WebSocketContext context = property.WebSocketContext;
31 var queryParameters = HttpUtility.ParseQueryString(context.RequestUri.Query);
32 string content = string.Empty;
33 
34 if (!message.IsEmpty)
35 {
36 byte[] body = message.GetBody<byte[]>();
37 content = Encoding.UTF8.GetString(body);
38 }
39 
40 // Do something with the content/queryParams
41 // ...
42 
43 string str = null;
44 if (string.IsNullOrEmpty(content)) // Connection open message
45 {
46 str = "Opening connection from user " +
47 queryParameters["Name"].ToString();
48 }
49 else // Message received from client
50 {
51 str = "Received message: " + content;
52 }
53 wcf.websocket.forweb.LogHelper.log.Error(str);
54 _callback.Send(CreateMessage(str));
55 }
56 
57 private Message CreateMessage(string content)
58 {
59 Message message = ByteStreamMessage.CreateMessage(
60 new ArraySegment<byte>(
61 Encoding.UTF8.GetBytes(content)));
62 message.Properties["WebSocketMessageProperty"] =
63 new WebSocketMessageProperty { MessageType = WebSocketMessageType.Text };
64 
65 return message;
66 }
67 }

View Code

View Code

二.新建WEB项目,在类型中引用第一步建立的WCF服务库Wcf.Duplex.Library。

二.新建WEB项目,在档次中援引第一步建立的WCF服务库Wcf.Duplex.Library。

1.打开Global.asax.cs的文件,在Application_Start增添以下代码:

1.打开Global.asax.cs的文件,在Application_Start增添以下代码:

RouteTable.Routes.Add(new ServiceRoute("EchoService",new ServiceHostFactory(),typeof(EchoService)));
RouteTable.Routes.Add(new ServiceRoute("EchoService",new ServiceHostFactory(),typeof(EchoService)));

 

 

讲明:增添服务路由的时候,路由前缀能够随便设置;瑟维斯Type,须求设置为WCF服务库的EchoService类。

证实:扩充服务路由的时候,路由前缀可以任由设置;ServiceType,须要安装为WCF服务库的EchoService类。

2.配置WEB.Config:

2.配置WEB.Config:

亚洲必赢手机 9亚洲必赢手机 10

亚洲必赢手机 11亚洲必赢手机 12

<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

<services>

<service name="Wcf.Duplex.Library.EchoService"><!--此处为服务类,需要修改为本项目的服务类-->
<endpoint address=""

binding="customBinding"

bindingConfiguration="webSocket"

contract="Wcf.Duplex.Library.IWebSocketEcho" /><!--此处为服务的协议接口,需要修改为本项目对应的服务接口-->
</service>
</services>
<bindings>
<customBinding>
<binding name="webSocket">
<byteStreamMessageEncoding/>
<httpTransport>
<webSocketSettings transportUsage="Always"

createNotificationOnConnection="true"/>
</httpTransport>
</binding>
</customBinding>
</bindings>
</system.serviceModel>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

<services>

<service name="Wcf.Duplex.Library.EchoService"><!--此处为服务类,需要修改为本项目的服务类-->
<endpoint address=""

binding="customBinding"

bindingConfiguration="webSocket"

contract="Wcf.Duplex.Library.IWebSocketEcho" /><!--此处为服务的协议接口,需要修改为本项目对应的服务接口-->
</service>
</services>
<bindings>
<customBinding>
<binding name="webSocket">
<byteStreamMessageEncoding/>
<httpTransport>
<webSocketSettings transportUsage="Always"

createNotificationOnConnection="true"/>
</httpTransport>
</binding>
</customBinding>
</bindings>
</system.serviceModel>

View Code

View Code

 

 

3.在此时此刻项目中伸张页面testWebSocket.html,使用WebSocket调用服务

3.在眼下项目中加进页面testWebSocket.html,使用WebSocket调用服务

亚洲必赢手机 13亚洲必赢手机 14

亚洲必赢手机 15亚洲必赢手机 16

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>WebSockets客户端示例</title>
</head>
<script>
var webSocket;
function connect() {
try {
var readyState = new Array("正在连接", "已建立连接", "正在关闭连接", "已关闭连接");
var host = 'ws://localhost:61413' +
window.location.pathname.replace('testWebSocket.html', 'EchoService') +
'?Name=liza';
webSocket = new WebSocket(host);
var message = document.getElementById("message");
message.innerHTML += "<p>Socket状态:" + readyState[webSocket.readyState] + "</p>";
webSocket.onopen = function () {
message.innerHTML += "<p>Socket状态:" + readyState[webSocket.readyState] + "</p>";
}
webSocket.onmessage = function (msg) {
message.innerHTML += "<p>接收信息:" + msg.data + "</p>";
}
webSocket.onclose = function () {
message.innerHTML += "<p>Socket状态:" + readyState[webSocket.readyState] + "</p>";
}
}
catch (exception) {
message.innerHTML += "<p>有错误发生</p>";
}
}
function send() {
var text = document.getElementById("text").value;
var message = document.getElementById("message");
if (text == "") {
message.innerHTML += "<p>请输入一些文字</p>";
return;
}
try {
webSocket.send(text);
message.innerHTML += "<p>发送数据:" + text + "</p>";
}
catch (exception) {
message.innerHTML += "<p>发送数据出错</p>";
}
document.getElementById("text").value = "";
}
function disconnect() {
webSocket.close();
}
</script>
<body>
<h1>WebSocket客户端示例</h1>
<div id="message"></div>
<p>请输入一些文字</p>
<input id="text" type="text">
<button id="connect" onclick="connect();">建立连接</button>
<button id="send" onclick="send();">发送数据</button>
<button id="disconnect" onclick="disconnect();">断开连接</button>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>WebSockets客户端示例</title>
</head>
<script>
var webSocket;
function connect() {
try {
var readyState = new Array("正在连接", "已建立连接", "正在关闭连接", "已关闭连接");
var host = 'ws://localhost:61413' +
window.location.pathname.replace('testWebSocket.html', 'EchoService') +
'?Name=liza';
webSocket = new WebSocket(host);
var message = document.getElementById("message");
message.innerHTML += "<p>Socket状态:" + readyState[webSocket.readyState] + "</p>";
webSocket.onopen = function () {
message.innerHTML += "<p>Socket状态:" + readyState[webSocket.readyState] + "</p>";
}
webSocket.onmessage = function (msg) {
message.innerHTML += "<p>接收信息:" + msg.data + "</p>";
}
webSocket.onclose = function () {
message.innerHTML += "<p>Socket状态:" + readyState[webSocket.readyState] + "</p>";
}
}
catch (exception) {
message.innerHTML += "<p>有错误发生</p>";
}
}
function send() {
var text = document.getElementById("text").value;
var message = document.getElementById("message");
if (text == "") {
message.innerHTML += "<p>请输入一些文字</p>";
return;
}
try {
webSocket.send(text);
message.innerHTML += "<p>发送数据:" + text + "</p>";
}
catch (exception) {
message.innerHTML += "<p>发送数据出错</p>";
}
document.getElementById("text").value = "";
}
function disconnect() {
webSocket.close();
}
</script>
<body>
<h1>WebSocket客户端示例</h1>
<div id="message"></div>
<p>请输入一些文字</p>
<input id="text" type="text">
<button id="connect" onclick="connect();">建立连接</button>
<button id="send" onclick="send();">发送数据</button>
<button id="disconnect" onclick="disconnect();">断开连接</button>
</body>
</html>

View Code

View Code

 

 



 同种类其余文章:何以选取HTML5的WebSocket落成网页与服务器的双工通讯(一)

 同连串其余小说:怎样行使HTML5的WebSocket已毕网页与服务器的双工通信(一)

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图