HTML5 WebSocket establish a Socket connection with C #

A, WebSocket

Outline

HTML5 WebSocket is a protocol provided by the start of full-duplex communication over a single TCP connection.

WebSocket enables exchange of data between the client and the server easier, allowing the server actively push data to the client. In the WebSocket API, the browser and the server only needs to complete a handshake, you can directly create a persistent connection between the two, and two-way data transmission.

Sent to the browser via JavaScript WebSocket server request to establish a connection after the connection is established, the client and the server can directly exchange data via TCP connection. When you get the Web Socket connection, you can send data to the server through the send () method, and to receive the data returned by the server onmessage event.

The following WebSocket API is used to create objects.

var Socket = new WebSocket(url, [protocol] );

The above code first parameter url, specify the URL connection. The second parameter is optional protocol, the sub-protocol specified acceptable.

WebSocket property

Socket.readyState readyState read-only attribute indicates the connection state, it can be the following values:

  • 0 - indicates that the connection has not been established.
  • 1-- indicates that the connection has been established, you can communicate.
  • 2 - represents an ongoing connection closed.
  • 3 - indicates that the connection has been closed or the connection can not be opened.

Socket.bufferedAmount bufferedAmount read-only attribute has been send () are placed in a queue awaiting transmission, but the number of bytes in UTF-8 text has not been issued.

WebSocket event


Triggered when the connection is established open Socket.onopen
triggered when the client receives the message Socket.onmessage server data
is triggered when an error occurs error Socket.onerror communication
triggered when the connection is closed close Socket.onclose

WebSocket method

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

Websocket handshake request

Client requests

GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: example.com
Origin: http://example.com
Sec-WebSocket-Key: sN9cRrP/n9NdMgdcy2VJFQ==
Sec-WebSocket-Version: 13

Server response

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: fFBooB7FAkLlXgRSz0BT3v4hq5s=
Sec-WebSocket-Location: ws://example.com/
  • Connection must be set to Upgrade, it means that the client wishes to connect to upgrade.
  • Upgrade field must be set Websocket, expressed the wish to upgrade to Websocket agreement.
  • Sec-WebSocket-Key is a random string, the server will use these data to construct a message digest of SHA-1. The "Sec-WebSocket-Key" plus a special string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", and SHA-1 digest is calculated, followed by BASE-64 encoding the result as "Sec-WebSocket-Accept "header value is returned to the client. Doing so, it is possible to avoid mistaken for normal HTTP request is Websocket protocol.

Websocket port

Websocket use ws wss or uniform resource identifier, similar to HTTPS, which represents Websocket wss over the TLS. Such as:

ws://example.com/wsapi
wss://secure.example.com/

Websocket use the same TCP and HTTP port, you can bypass most firewalls limit. By default, Websocket protocol uses port 80; run at over TLS, 443 using the default port.

Client code

<! DOCTYPE the HTML> 
<HTML> 
   <head> 
   <Meta charset = "UTF-. 8"> 
   <title> novice tutorial (runoob.com) </ title> 
    
      <Script type = "text / JavaScript"> function WebSocketTest () 
         { IF ( "the WebSocket" in window) 
            { 
               Alert ( "your browser supports the WebSocket!" ); // open a socket Web var WS = new new the WebSocket ( "WS: // localhost: 9998 / echo" ); 
               WS.OnOpen = function () 
               { // the Web is the Socket connection, using the send () method for transmitting data 
                  ws.send ( "transmit data"
         
            
               
               
               
                
                  ); 
                  Alert ( "data transmission ..." ); 
               }; 
                
               ws.onmessage = function (EVT) 
               { 
                  var received_msg = evt.data; 
                  Alert ( "data has been received ..." ); 
               }; 
                
               ws.onclose = function () 
               { 
                  // close the WebSocket 
                  Alert ( "connection closed ..." ); 
               }; 
            } 
            
            the else 
            { 
               // browser does not support the WebSocket 
               Alert ( "your browser does not support WebSocket!");
            }
         }
      </script>
        
   </head>
   <body>
   
      <div id="sse">
         <a href="javascript:WebSocketTest()">运行 WebSocket</a>
      </div>
      
   </body>
</html>

Two, C # Socket connection established

1, using the original socket

https://www.cnblogs.com/xqaizx/p/9446863.html

2, the use of third-party libraries

c # can choose websocket-sharp to achieve websocket Server. Or https://github.com/Azure/DotNetty

class Program
    {
        static void Main(string[] args)
        {
            var wssv = new WebSocketServer(10086);
            wssv.AddWebSocketService<ScannerHandler>("/scan");
            wssv.Start();
            if (wssv.IsListening)
            {
                Console.WriteLine("Listening on port {0}, and providing WebSocket services:", wssv.Port);
                foreach (var path in wssv.WebSocketServices.Paths)
                    Console.WriteLine("- {0}", path);
            }

            Console.WriteLine("\nPress Enter key to stop the server...");
            Console.ReadLine();

            wssv.Stop();
        }
    }

    public class ScannerHandler : WebSocketBehavior
    {
        protected override void OnMessage(MessageEventArgs e)
        {
            if(e.Data == "scan")
            {
                ScanResult result = ScanerHelper.Scan("D:\\test.jpg");
                if (result.Success)
                {
                    Console.WriteLine("scan success");
                    Send("scan success");
                }
                else
                {
                    Send("scan eror");
                }
            }
           
        }
    }

Guess you like

Origin www.cnblogs.com/springsnow/p/11112765.html