How does H5 WebSocket communicate with C,
As the next-generation Web standard, HTML5 has many notable new features, such as Canvas, local storage, multimedia programming interfaces, and WebSocket. WebSocket provides a two-way channel based on TCP connection between the browser and the server. Web developers can easily use WebSocket to build real-time web applications. The purpose of HTML5 WebSocket is to replace the polling and Comet technologies, so that the client browser can have real-time communication capabilities like the Desktop System in the C/S architecture. Compared with polling and Comet technologies, WebSocket has great performance advantages in terms of data transmission stability and data transmission volume.
The following is a simple example to illustrate how websocket interacts with the front and back ends:
1 html page
First, determine whether the browser supports WebSocket. If this feature exists, open a specific uri for data interaction.
1
2 C # websocket server
1 using System; 2 using Fleck; 3 using Newtonsoft. json; 4 namespace WebSocketNet 5 {6 class Program 7 {8 static void Main (string [] args) 9 {10 11 // Fleck12 var server = new WebSocketServer ("ws: // 0.0.0.0: 8181 "); 13 server. start (socket => 14 {15 socket. onOpen = () => 16 {17 Console. writeLine ("Open! "); 18 socket. Send (" hello "); 19}; 20 21 socket. OnClose = () => Console. WriteLine (" Close! "); 22 socket. onMessage = message => 23 {24 Console. writeLine (message); 25 // use websocket to log on to 26 dynamic o = JsonConvert. deserializeObject <user> (message); 27 var pwd = o. pwd; 28 var uid = o. uid; 29 if (uid = "admin" & uid = "admin") 30 {31 socket. send ("login success"); 32} 33 else34 {35 socket. send ("login fail"); 36} 37 38}; 39 40}); 41 42 Console. readLine (); 43} 44} 45 public class user46 {47 public string uid {get; set;} 48 public string pwd {get; set;} 49} 50}
3. Run