Original http://www.oseye.net/user/kevin/blog/79
I plan to explore WebSocket in the following blog posts:
- WebSocket simple use (1)-Concept
- WebSocket (2)-Client
- WebSocket (3)-Server
- WebSocket simple use (4)-complete instance
- WebSocket simple use (5)-simulate the keyboard connection Function
Background:
A few days ago, the boss suddenly found a function of link keyboard. I thought it might be implemented using WebSocket. In addition, the recent HTML5 call is getting higher and higher, and I think it is necessary to study HTML5.
For example, in the handshake protocol described in the concept article, the client provides APIs by the browser, so you only need to use JavaScript For simple calls, and the server must implement it by yourself, the server will talk about it in the next blog.
WebSocket JavaScript interface definition:
- [Constructor (inDOMString url, optional inDOMString protocol)]
- InterfaceWebSocket {
- Readonly attribute DOMString URL;
- // Ready state
- Constunsignedshort CONNECTING = 0;
- Constunsignedshort OPEN = 1;
- Constunsignedshort CLOSED = 2;
- Readonly attribute unsignedshort readyState;
- Readonly attribute unsignedlong bufferedAmount;
-
- // Networking
- Attribute Function onopen;
- Attribute Function onmessage;
- Attribute Function onclose;
- Boolean send (inDOMString data );
- Void close ();
- };
- WebSocketimplementsEventTarget;
A Brief Introduction to interface methods and attributes:
- ReadyState indicates that the connection has four states:
CONNECTING (0): indicates that no connection has been established;
OPEN (1): A connection has been established for communication;
CLOSING (2): closes the connection by CLOSING the handshake;
CLOSED (3): the connection is CLOSED or cannot be opened;
- The url represents the network address of the WebSocket server. The protocol is generally "ws" or "wss (encrypted communication)". The send method is to send data to the server;
- The close method is to close the connection;
- The onopen connection is established, that is, the event triggered by the handshake;
- Event triggered when onmessage receives a message from the server;
- Event triggered by an onerror exception;
- Onclose: The event triggered by closing the connection;
An example of using JavaScript to call a browser interface is as follows:
- Var wsServer = 'ws: // localhost: 8888/demo'; // server address
- Var websocket = newWebSocket (wsServer); // create a WebSocket object
- Websocket. send ("hello"); // send a message to the server
- Alert (websocket. readyState); // view the current status of websocket
- Websocket. onopen = function (evt ){
- // A connection has been established.
- };
- Websocket. onclose = function (evt ){
- // The connection has been closed
- };
- Websocket. onmessage = function (evt ){
- // Receives the Server Message and extracts it using evt. data.
- };
- Websocket. onerror = function (evt ){
- // Exception
- };