Use html5 websocket to implement websocket chat rooms

Source: Internet
Author: User

Comments: Use html5 websocket to implement a chat room.

What is websocket?

The WebSocket protocol is a new protocol introduced by html5. it aims to implement full duplex communication between browsers and servers. 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, there are two advantages to doing so
 
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, There is only 2 k
 
2. The server can actively push messages to the client instead of querying them.
 
Concepts and benefits are everywhere on the Internet. I will not repeat them here. Let's take a look at its principles and then write a chat room for a web version.
 
Handshake

In addition to the three-way handshake of TCP connections, an additional handshake is required for the client to establish a connection with the server in the websocket protocol.
 
The client sends a request to the server.
 

The Code is as follows:
GET, HTTP, 1.1
Upgrade: websocket
Connection: Upgrade
Host: 127.0.0.1: 8080
Origin: <a href = "http://test.com"> http://test.com </a>
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: OtZtd55qBhJF2XLNDRgUMg =
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
User-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

Server Response
 
The Code is as follows:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: xsOSgr30aKL2GNZKNHKmeT1qYjA =

The "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 ).
 
Websocket API

After the handshake, the browser establishes a connection with the server, and the two can communicate with each other. Websocket APIs are really simple. Let's look at W3C definitions.
 

The Code is as follows:
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 EventHandler onopen;
Attribute EventHandler onerror;
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 );
};

Create websocket
 
The Code is as follows:
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.
 
Disable socket

The Code is as follows:
Ws. close ();

 
You can call the close () method of the webservice instance to disable webservice. Of course, you can also input a code and string to explain why webservice is disabled.
 
Several callback function handles
 
Because of its asynchronous execution, callback functions are indispensable and there are four important
 
Onopen: called after the connection is created
Onmessage: called after receiving a message from the server
Onerror: called when an error occurs
Onclose: called when the connection is closed

You can see what the name is. Every callback function will pass in an Event object, and you can access the message through event. data.
 
Use API
 
We can assign values to the callback function after the socket is successfully created.
 

The Code is as follows:
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 bind events.

The Code is as follows:
Ws = new WebSocket (address );
Ws. 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 + '> }');

Client implementation
In fact, the implementation of the client is relatively simple, except for some simple functions related to websocket, such as automatic focus, Return key event processing, and automatic position of the message box to the bottom.


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.