Node (websocket)

Source: Internet
Author: User
Tags button type emit sendmsg

WebSocket was originally a feature of long links under HTML5 and is currently supported by many browsers.

In the WebSocket protocol, a handshake is first exchanged over HTTP to explicitly upgrade the protocol to WebSocket. A TCP channel is also established to exchange data in frame frames.

In the node environment, the basic functions can be achieved as follows:

First NPM Install Socket.io

1, app.js, initialize Socket.io

var function () {  console.log (' Express server listening on port ' + app.get (' Port ');}); var io     = require (' Socket.io '). Listen (SRV); server.initserver (IO);

2, Server.js implement server-side code

function (IO) {        io.on (' connection ',function(socket) {        console.log (' connection ');        Socket.on (' disconnect ',function(msg) {            console.log (' disconnect ');        });                Socket.on (' msg1 ',function(msg) {            console.log (msg);                        Socket.emit (' back ', {key: ' Fredric&sinny '});     });}

3. Client code

<! DOCTYPE html> var socket = io.connect (' http://localhost:3000 ');         function sendmsg () {               console.log (' Start sendmsg ');        Socket.emit (' Msg1 ', {key: ' Fredric '});        Socket.on (' back ',function(msg) {        alert (msg.key);    });     </script>

The browser-side debug network interface is as follows:

Node (websocket)

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.