Building WebSocket with C

Keywords: C# socket html5 Javascript

WebSocket is a full duplex communication protocol provided by HTML5 on a single TCP connection.

WebSocket makes the data exchange between the client and the server easier, allowing the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete one handshake, and they can directly create a persistent connection and carry out two-way data transmission.

In WebSocket API, browser and server only need to make a handshake, and then a fast channel is formed between browser and server. The two can directly transmit data to each other.

Today, I will use C to build WebSocket server to demonstrate the communication process of WebSocket.

I. events, properties and methods in WebSocket

Properties:

Socket.readyState read only property readyState indicates the connection state, which can be the following values:
                                                0 - indicates that the connection has not been established.
                                                1 - indicates that the connection has been established and can be communicated.
                                                2 - indicates that the connection is closing.
                                                3 - indicates that the connection is closed or cannot be opened.
Socket.bufferedAmount read only property bufferedAmount has been put into the queue by send() to wait for transmission, but the number of UTF-8 text bytes that have not yet been issued

Event:

Event event handler description
Triggered when the open Socket.onopen connection is established    
Triggered when the message Socket.onmessage client receives data from the server
Error Socket.onerror triggered when communication error occurs    
Triggered when the close Socket.onclose connection is closed    

Methods:

Socket.send() uses connection to send data    
Socket.close() closes the connection

2. With a general understanding, we will start to implement such an example.

1. Client

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body >
        <div style="margin-left: 650px;">
            <form id="Form"> 
                <input type="input" name="" id="SendInfo" value="" />
                <button type="submit">Submission</button>
            </form>
    
            <div id="hello" style="border: dashed 1px black;height: 500px;width: 500px;margin-top: 10px;">
            
            </div>
        </div>
        
    </body>
    <script type="text/javascript">
        var test=function(){
            
            var print=document.getElementById('hello');
            var form = document.getElementById('Form');
            var input = document.getElementById('SendInfo');
            print.innerHTML += "connecting to server ..<br/>";        
            window.ws = new WebSocket('ws://localhost:9898/');      //Monitor webscoket Service port
        
            //Monitor message status
            ws.onmessage=function(eve){
                print.innerHTML+=eve.data+'<br/>'
            }
            
            //Monitor link status
            ws.onopen=function(){
                print.innerHTML+='connection open <br/>'
            }
            
            //Monitor off status
            ws.onclose = function () {
                print.innerHTML += 'connection closed<br/>';
            }

               //Send message to server
               form.addEventListener('submit',function(e){
                   e.preventDefault();
                   var val="Client:"+input.value;
                   ws.send(val);
                   input.value="";
               })
               
        }
        
        window.onload=test();
    </script>
</html>

 

2. The server creates a C console program

using Fleck;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebScoket
{
    class Program
    {
        static void Main(string[] args)
        {
            var allScokets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://127.0.0.1:9898");    //Establish webscoket Server instance
            server.Start(scoket=> {
                scoket.OnOpen = () =>                   
                {
                    Console.WriteLine("Open");
                    allScokets.Add(scoket);
                };
                scoket.OnClose = () =>
                {
                    Console.WriteLine("Close");
                    allScokets.Remove(scoket);
                };
                scoket.OnMessage =message => {
                    Console.WriteLine(message);
                    allScokets.ToList().ForEach(s=>s.Send(message));
                };
            });

            var input = Console.ReadLine();
            while (input != "exit")
            {
                foreach (var socket in allScokets.ToList())
                {
                    socket.Send("Server:"+input);
                }
                input = Console.ReadLine();
            }

        }
    }
}

 

3. Operation effect

 

Posted by Brian on Thu, 17 Oct 2019 03:44:39 -0700