C # implementation of the websocket timely communication protocol (Tutorial ),

Source: Internet
Author: User

C # implementation of the websocket timely communication protocol (Tutorial ),

 

1: Websocket has java, nodejs, python, PHP, and other versions. I am using C3 and Fleck on the server side. The following describes how to use websocket on the client and server:

2: Before starting, let's take a look at which browsers support websocket:

Websocket server support:

3: Next we will use the C # console program to implement direct communication between the client and the server:

Open VS2015 to create a project Webshoufa (for example)

 

Server example:

 

Open the main Program and import it to Program. CS.

The code for writing the main link push is as follows:

FleckLog.Level = LogLevel.Debug;            var allSockets = new List<IWebSocketConnection>();            var server = new WebSocketServer("ws://0.0.0.0:7181");            server.Start(socket =>            {                socket.OnOpen = () =>                {                    Console.WriteLine("Open!");                    allSockets.Add(socket);                };                socket.OnClose = () =>                {                    Console.WriteLine("Close!");                    allSockets.Remove(socket);                };                socket.OnMessage = message =>                {                    Console.WriteLine(message);                    allSockets.ToList().ForEach(s => s.Send("Echo: " + message));                };            });
View Code

The above code:Important Note 【Fleck]In this instance, the server uses Fleck as follows:

Fleck is a WebSocket server implementation in C. From the Nugget project branch, Fleck does not need to inherit, containers or other references.The sample code is as follows (The following is an example of returning the image to the client.)Before implementation, the. NET platform must be above 4.5 to run,

As mentioned above. In this example, we define the port strength to reference the WebSocketServer service, and the format is fixed. Refer to writing.

 

Example code 1 is as follows:

1 var server = new WebSocketServer("ws://localhost:7181");2 server.Start(socket =>3   {4     socket.OnOpen = () => Console.WriteLine("Open!");5     socket.OnClose = () => Console.WriteLine("Close!");6     socket.OnMessage = message => socket.Send(message);7   });
View Code

Example code 2 is as follows (Security Key Version)

Ar server = new WebSocketServer ("wss: // 0.0.0.0: 8431"); server. certificate = new X509Certificate2 ("MyCert. pfx "); server. start (socket => {//... normal usage });
View Code

Start to trigger server. start service output code. The difference between the above two instance code outputs is that to enable secure connection requires two things: use this solution wss to replace ws, and point Fleck to an x509 Certificate containing the public key and private key. Details are acceptableRefer to the official website API:Https://github.com/statianzo/Fleck

 

Next, write the code that triggers the keyboard response:

var input = Console.ReadLine();            while (input != "exit")            {                foreach (var socket in allSockets.ToList())                {                    socket.Send(input);                }                input = Console.ReadLine();            }
View Code

Code parsing: The above definition input = Console. ReadLine (); consists of the first output parameter

If the input is not empty, the next event is triggered.

This completes the server-side sample development.

 

Client page request side display (Browser Side)

1: Create a client project, which can be a web page or webform page.

2: My example is to use webform to create an example:

Here, we only implement real-time interactive display of data. If you need data storage services, You need to perform background encoding.

3: Demo code:

JS details

 

<Script type = "text/javascript"> var start = function () {var inc = document. getElementById ('comming'); var wsImpl = window. webSocket | window. using websocket; var form = document. getElementById ('sendform'); var input = document. getElementById ('sendtext'); inc. innerHTML + = "connecting to server .. <br/> "; // create a new websocket. The new connection port is 7181 window. ws = new wsImpl ('ws: // localhost: 7181/'); // when data is sent from the server service center, continue to run ws. onmessage = function (evt) {inc. innerHTML + = evt. data + '<br/>';}; // when the linked object is found to be successfully connected to the server, the system prompts that the ws can be opened normally. onopen = function () {inc. innerHTML + = '.. connection open <br/> ';}; // when the connection object is not found and the server is successfully docked, the system prompts that the connection failed. Do not close ws individually. onclose = function () {inc. innerHTML + = '.. connection closed <br/> ';} form. addEventListener ('submit ', function (e) {e. preventDefault (); var val = input. value; ws. send (val); input. value = "" ;}) ;}window. onload = start; </script>
View Code

 

Note the ws key definitions in window. ws = new wsImpl ('ws: // localhost: 7181/') in the sample code snippet above.

Two things are required to enable secure connection: Use the scheme wss to replace ws and point Fleck to an x509 Certificate containing the public key and private key.

And use window. onload = start; function.

 

Note:

 

1. Place the script code at the bottom of the Web page. when running the script code, you can ensure that the object to be operated has been loaded.
2. Run the script code through window. onload.

 

For details about the usage of window. onload in JS functions, refer:

Http://www.softwhy.com/forum.php? Mod = viewthread & tid = 6191.

Code 2: Call the control entity to trigger an event:

<body>    <form id="sendForm">        <input id="sendText" placeholder="Text to send" />    </form>    <pre id="incomming"></pre></body>
View Code

The preceding page is developed for implementing data push through client web page access.

Now, the two projects are generated and started one by one in order. Note that you must start both projects before testing and verifying the results.

 

Start the client page and console Program (then refresh the client page)

 

When the client interacts with the server, enter hello, peak or XXXX information, and the server receives data within almost zero error time. You can also enter information in the server window. For example, are you going to Alxa for a business trip?

It's amazing. Now you can add your favorite interface business logic. Do you think the frontend and backend communication has become simple? Strong or not powerful? Great !!!!

OK. Now we have finished the tutorial,This article focuses on the following two development sets, which are particularly important in the development process:

1:. NET 4.5 added WebSocket
2:Server:
Var listener = new HttpListener ();
Listener. Prefixes. Add ("http: // X: 8080 /");
Listener. Start ();
Var context = await listener. GetContextAsync ();
Var wsContext = await context. AcceptWebSocketAsync (null );
Var ws = wsContext. WebSocket;
3:Client:
Var ws = new ClientWebSocket ();
Await ws. ConnectAsync (new Uri ("ws: // 127.0.0.1: 8080"), CancellationToken. None );

OK. Thank you for reading the small example. If you have any shortcomings, please give us more advice and discuss it together. The following sections upload the instance code program for your reference and improve it.

 

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.