How to Use HTML5 WebSocket to implement duplex communication between webpages and servers (2), html5websocket

Source: Internet
Author: User

How to Use HTML5 WebSocket to implement duplex communication between webpages and servers (2), html5websocket

This series of server-side duplex communication includes two implementation methods: 1. Using Socket to build; 2. Using WCF to build. This article uses WCF to build server-side duplex communication, and the client also uses Html5 WebSocket Technology for calling.

1. Create the WCF Service Library Wcf. Duplex. Library:

1. Define the service interface of the Protocol:

[ServiceContract]
Public interface IWebSocketEchoCallback
{
[OperationContract (IsOneWay = true, Action = "*")]
Void Send (Message message );
}

[ServiceContract (CallbackContract = typeof (IWebSocketEchoCallback)]
Public interface IWebSocketEcho
{
[OperationContract (IsOneWay = true, Action = "*")]
Void Receive (Message message );
}

Note:

Actions in OperationContract must be set.

In the IWebSocketEcho interface, only one OperationContract (IsOneWay = true, Action = "*") method entry can be defined. Otherwise, an error will be reported during WebSocket connection.

In the IWebSocketEchoCallback callback interface, you can define multiple OperationContract (IsOneWay = true, Action = "*") methods.

2. Implement the service protocol, define a clock, call the callback method regularly, and send information to the client:

Public class EchoService: IWebSocketEcho
{

IWebSocketEchoCallback _ callback = null;

Public EchoService ()
{

// Obtain the callback Channel
_ Callback =
OperationContext. Current. GetCallbackChannel <IWebSocketEchoCallback> ();

Timer time = new Timer (10000 );
Time. Elapsed + = time_Elapsed;
Time. Start ();
}
Void time_Elapsed (object sender, ElapsedEventArgs e)
{
_ Callback. Send (CreateMessage ("Message From WebSockets Host" + "" + DateTime. Now. ToString ("yyyy-MM-dd HH: mm: ss ")));
}
Public void Receive (Message message)
{
If (message = null)
{
Throw new ArgumentNullException ("message ");
}

WebSocketMessageProperty property =
(WebSocketMessageProperty) message. Properties ["WebSocketMessageProperty"];
WebSocketContext context = property. WebSocketContext;
Var queryParameters = HttpUtility. ParseQueryString (context. RequestUri. Query );
String content = string. Empty;

If (! Message. IsEmpty)
{
Byte [] body = message. GetBody <byte []> ();
Content = Encoding. UTF8.GetString (body );
}

// Do something with the content/queryParams
//...

String str = null;
If (string. IsNullOrEmpty (content) // Connection open message
{
Str = "Opening connection from user" +
QueryParameters ["Name"]. ToString ();
}
Else // Message received ed from client
{
Str = "Received message:" + content;
}
Wcf. websocket. forweb. LogHelper. log. Error (str );
_ Callback. Send (CreateMessage (str ));
}

Private Message CreateMessage (string content)
{
Message message = ByteStreamMessage. CreateMessage (
New ArraySegment <byte> (
Encoding. UTF8.GetBytes (content )));
Message. Properties ["WebSocketMessageProperty"] =
New WebSocketMessageProperty {MessageType = WebSocketMessageType. Text };

Return message;
}
}

2. Create a WEB project and reference the WCF Service Library Wcf. Duplex. Library created in step 1 in the project.

1. Open the Global. asax. cs file and add the following code in Application_Start:

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

Note: When adding a service route, you can set the route prefix as needed. ServiceType, you need to set it to the EchoService class of the WCF Service library.

2. Configure WEB. Config:

<System. serviceModel>
<ServiceHostingEnvironment aspNetCompatibilityEnabled = "true" multipleSiteBindingsEnabled = "true"/>

<Services>

<Service name = "Wcf. Duplex. Library.EchoService"><! -- This is a service class and needs to be modified to the service class of this project -->
<Endpoint address = ""

Binding = "customBinding"

BindingConfiguration = "webSocket"

Contract = "Wcf. Duplex. Library. IWebSocketEcho"/><! -- This is the service protocol interface. You need to modify it to the Service Interface corresponding to this project. -->
</Service>
</Services>
<Bindings>
<CustomBinding>
<Binding name = "webSocket">
<ByteStreamMessageEncoding/>
<HttpTransport>
<WebSocketSettings transportUsage = "Always"

CreateNotificationOnConnection = "true"/>
</HttpTransport>
</Binding>
</CustomBinding>
</Bindings>
</System. serviceModel>

3.add the page testwebsocket.html in the current project and use WebSocket to call the service.

<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "UTF-8"/>
<Title> WebSockets client example </title>
</Head>
<Script>
Var webSocket;
Function connect (){
Try {
Var readyState = new Array ("connecting", "established connection", "Closing connection", "Closing connection ");
Var host = 'ws: // localhost: 61413 '+
Registry.location.pathname.replace('testwebsocket.html ', 'echoservice') +
'? Name = liza ';
WebSocket = new WebSocket (host );
Var message = document. getElementById ("message ");
Message. innerHTML + = "<p> Socket status:" + readyState [webSocket. readyState] + "</p> ";
WebSocket. onopen = function (){
Message. innerHTML + = "<p> Socket status:" + readyState [webSocket. readyState] + "</p> ";
}
WebSocket. onmessage = function (msg ){
Message. innerHTML + = "<p> received information:" + msg. data + "</p> ";
}
WebSocket. onclose = function (){
Message. innerHTML + = "<p> Socket status:" + readyState [webSocket. readyState] + "</p> ";
}
}
Catch (exception ){
Message. innerHTML + = "<p> An error occurred </p> ";
}
}
Function send (){
Var text = document. getElementById ("text"). value;
Var message = document. getElementById ("message ");
If (text = ""){
Message. innerHTML + = "<p> enter some text </p> ";
Return;
}
Try {
WebSocket. send (text );
Message. innerHTML + = "<p> send data:" + text + "</p> ";
}
Catch (exception ){
Message. innerHTML + = "<p> An error occurred while sending data </p> ";
}
Document. getElementById ("text"). value = "";
}
Function disconnect (){
WebSocket. close ();
}
</Script>
<Body>
<H1> WebSocket client example <Div id = "message"> </div>
<P> enter some text </p>
<Input id = "text" type = "text">
<Button id = "connect" onclick = "connect ();"> establish a connection </button>
<Button id = "send" onclick = "send ();"> send data </button>
<Button id = "disconnect" onclick = "disconnect ();"> disconnect </button>
</Body>
</Html>

 

Other articles in the same series: How to Use HTML5 WebSocket to implement duplex communication between webpages and servers (1)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.