Get through B/S and C/s! Let HTML5 websocket and. NET sockets share the same server!

Source: Internet
Author: User
Tags server port

With the increasingly mature and popularization of HTML5 websocket technology, we can use the websocket to make it easier to get through BS and CS--because the websocket in B/s can be directly connected to the server of C/s and the two-way communication. As shown in the following:

  

I. Requirements for the socket server

We can try to get the socket server to transparently support the WebSocket client, which means that the server developer does not care what the client is, but it can receive data, process it, and send the data uniformly. To do this, we can build a service-side framework that allows the framework to do its work transparently, which requires the framework to do the following:

(1) Whether the client TCP connection request succeeds if the first message contains a "websocket" tag, to determine whether it is a websocket client. If the client type is websocket, the following things are done automatically.

(2) Automatically complete the Web sokects handshake protocol.

(3) For each websokect data frame received, it can automatically parse it and isolate the real message content from it.

(4) When you send a message to the Websokect client, the server engine automatically encapsulates the message into a websokect data frame before sending it.

I realized in the striveengine of the above websocket transparent support, as to how the specific implementation, we can refer to Websokect standard protocol. Let's make a demo so that the. NET socket client and the WebSocket client can communicate with one Striveengine server in two directions at the same time.

two. b/S and C/s demo preparation

Based on Websokect, we use text messages in most cases, OK, then we build this demo based on text messages.

(1) Although websokect can use its HTML5 protocol to automate the independent identification of a message, there must be a way for our normal socket to identify a complete message.

(2) The usual method is to use a special message end identifier, that in this demo, we take ' Terminator ' as the message of the bar.

(3) based on (2), the Websokect must also add '/E ' at the end of the message when sending a message to the server.

three. Demo Implementation

Let's look at the effect of the demo running:

In the demo, both the WebSocket client and the. NET socket client can communicate with the same server.

1. Source Code Structure Description

The demo source includes a total of three items and an HTML file:

(1) Striveengine.simpledemoserver: Based on the striveengine development of the service side.

(2) Striveengine.simpledemoclient: Client based on Striveengine development.

(3) Striveengine.simpledemo: Client directly based on. NET socket development.

(4) websocketclient.html: Client based on HTML5 WebSocket. The same striveengine server is common to the first two clients.

Next, we focus on the WebSocket client implementation, the other. NET code, everyone directly to see the demo source code is good.

2.WebSocket Client Implementation

(1) HTML page layout

<Body>    <H3>Websockettest</H3>    <DivID= "Login">        <Div>            <inputID= "ServerIP"type= "text"placeholder= "Server IP"value= "127.0.0.1"Autofocus= "Autofocus" />            <inputID= "ServerPort"type= "text"placeholder= "Server Port"value= "9000" />            <inputID= "Btnconnect"type= "button"value= "Connection"onclick= "Connect ()" />        </Div>        <Div>            <inputID= "SendText"type= "text"placeholder= "Send Text"value= "I ' m WebSocket client!" />            <inputID= "Btnsend"type= "button"value= "Send"onclick= "Send ()" />        </Div>        <Div>            <Div>messages from the service side</Div>            <textareaID= "Txtcontent"cols= " the"rows= "Ten"ReadOnly= "ReadOnly"></textarea>        </Div>    </Div></Body>

(2) JS method implementation

<script>varsocket; functionConnect () {varHost = "ws://" + $ ("ServerIP"). Value + ":" + $ ("ServerPort"). Value + "/"Socket=NewWebSocket (host); Try{socket.  OnOpen =function(msg) {$ ("Btnconnect"). Disabled =true; Alert ("The connection was successful!" ");                }; Socket. onmessage =function(msg) {if(typeofMsg.data = = "string") {displaycontent (msg.data); }                    Else{alert ("Non-text message");                }                }; Socket. OnClose =function(msg) {alert ("Socket closed!") }; }            Catch(ex) {log (ex); }        }        functionSend () { var msg = $ ("SendText"). Value + ' + 'socket. Send        (msg); } window.onbeforeunload=function () {            Try{socket.close (); Socket=NULL; }            Catch(ex) {}}; function$ (ID) {returndocument.getElementById (ID);} Date.prototype.Format=function(FMT) {//Author:meizz            varo = {                "m+": This. GetMonth () + 1,//Month"D+": This. GetDate (),//Day"H +": This. GetHours (),//hours"m+": This. getminutes (),//points"S+": This. getseconds (),//seconds"q+": Math.floor (( This. GetMonth () + 3)/3),//Quarterly"S": This. Getmilliseconds ()//milliseconds            }; if(/(y+)/.test (FMT)) FMT = Fmt.replace (regexp.$1, ( This. getFullYear () + ""). substr (4-regexp.$1. length));  for(varKincho)if(NewRegExp ("(" + K + ")"). Test (FMT)) FMT = Fmt.replace (regexp.$1, (regexp.$1.length = = 1)? (O[k]): (("XX" + o[k]). substr ("" +o[k])); returnFMT; }        functiondisplaycontent (msg) {$ ("Txtcontent"). Value + = "\ r \ n" +NewDate (). Format ("Yyyy/mm/dd hh:mm:ss") + ":" +msg; }        functionOnKey (event) {if(Event.keycode = = 13) {send ();}} </script>

The emphasis in the JS code is marked out by the red font, and it is important to note that the Send method will automatically add a Terminator '+ ' to the end of the message when it sends the message.

four. Source code Download

Get through BS and CS demo source

If you have any suggestions or questions, please leave a message to me.

Get through B/S and C/s! Let HTML5 websocket and. NET sockets share the same server!

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.