Use html 5 websocket to create a cottage web chat room (handwritten C # server)

Source: Internet
Author: User

I was very interested in seeing html5 websocket in my previous blog. I can finally get rid of long polling. (For the implementation method before websocket, I can refer to an article on Developer Works, at the same time, I also talked about the basic concepts of websocket. What is websocket WebSocket is a new protocol introduced by html5. it aims to achieve full duplex communication between the browser and the server. Those who read the link above will surely have some knowledge about how low efficiency and high consumption (polling or comet) have been done in the past. In the websocket API, the browser and the server only need to do a handshake, and then a fast channel is formed between the browser and the server. Data can be directly transmitted to each other. At the same time, doing so has two advantages: 1. reduced communication transmission byte: Compared to the previous use of http to transmit data, the extra information transmitted by websocket is very small. According to Baidu, only 2 k 2. the server can actively push messages to the client, instead of querying about the concepts and benefits. It is everywhere on the Internet and will not go into details. Let's take a look at its principles, in addition to the three handshakes of TCP connections, the handshakes of the client and server in the websocket Protocol require an additional handshakes, in the latest protocol, the client sends a request to the server to copy the code GET/HTTP/1.1 Upgrade: websocketConnection: UpgradeHost: 127.0.0.1: 8080 Origin: http://test.comPragma : No-cacheCache-Control: no-cacheSec-WebSocket-Key: OtZtd55qBhJF2XLNDRgUMg = Sec-WebSocket-Version: 13Sec-WebSocket-Extensions: x-webkit-deflate-frameUser-Agent: mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36 copy code Server gives response HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: xsOSgr30aKL2GNZKNH KmeT1qYjA = "Sec-WebSocket-Key" in the request is random, and the server uses the data to construct a SHA-1 information digest. Add "Sec-WebSocket-Key" with a magic string "258eafa5-e914-4710995ca-c5ab0dc85b11 ". Use SHA-1 encryption, and then perform BASE-64 encoding. Use the result as the value of the "Sec-WebSocket-Accept" header and return it to the client (from Wikipedia ). After websocket API handshake, the browser establishes a connection with the server, and the two can communicate with each other. Websocket APIs are really simple. Look at W3C definition replication code enum BinaryType {"blob", "arraybuffer"}; [Constructor (DOMString url, optional (DOMString or DOMString []) protocols)] interface WebSocket: EventTarget {readonly attribute DOMString url; // ready state const unsigned short CONNECTING = 0; const unsigned short OPEN = 1; const unsigned short CLOSING = 2; const unsigned short CLOSED = 3; readonly attribute unsigned short readyState; readonly attribute unsigned long bufferedAmount; // networking attribute deleonopen; attribute deleonerror; attribute EventHandler onclose; readonly attribute DOMString extensions; readonly attribute DOMString protocol; void close ([Clamp] optional unsigned short code, optional DOMString reason); // messaging attribute EventHandler onmessage; attribute BinaryType binaryType; void send (DOMString data ); void send (Blob data); void send (ArrayBuffer data); void send (ArrayBufferView data) ;}; copy the code to create websocket ws = new WebSocket (address); // ws: // 127.0.0.1: 8080 call its constructor and pass in the address to create a websocket. It is worth noting that the address protocol must be ws/wss to close socket ws. close (); call the close () method of the webservice instance to close webservice. Of course, you can also input a code and string to explain why several callback function handles are closed due to its asynchronous execution, the callback function is indispensable. There are four important onopen: onmessage is called after the connection is created: onerror is called after the server message is received: onclose is called when an error occurs: when the connection is closed, you can call it to see what the name is. Each callback function will input an Event object, which can be passed through the event. data Access message using API we can assign a value for the callback function after the socket is successfully created to copy the code ws = new WebSocket (address); ws. onopen = function (e) {var msg = document. createElement ('div '); msg. style. color = '#0f0'; msg. innerHTML = "Server> connection open. "; msgContainer. appendChild (msg); ws. send ('{<' + document. getElementById ('name '). value + '>}') ;}; you can also copy the code ws = new WebSocket (address); ws by event binding. addEventListener ('open', function (e) {var msg = document. createElement ('div '); msg. style. color = '#0f0'; msg. innerHTML = "Server> connection open. "; msgContainer. appendChild (msg); ws. send ('{<' + document. getElementById ('name '). value + '>}') ;}); copy the code client to implement a simple client, in addition to some simple functions related to websocket, such as automatic focus, carriage return event processing, and automatic bottom location of message boxes, View Code is not described in detail.

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.