TCG Development Log (3) Socket.io

Source: Internet
Author: User
Tags emit

In order to let the Web side and the server can communicate with each other at any time, before the HTTP has a variety of wording, but now we can use websocket, at least on chrome.

Install Socket.io First

NPM Install Socket.io--save

On the server side, Socket.io and KOA can be combined:

Import Koa from ' Koa ';
Import IO from ' Socket.io '

Let app = new Koa ();
Let server = require (' http '). Server (App.callback ());

Let IO = new io (server);

After the end of all middleware loading in the app,

Io.on (' Connection ', socket=>{
Console.log ("here! Someone connected! ");
Socket.on (' foo ', data=>{
Console.log (data);
SetInterval (() =>socket.emit (' bar ', {text: "HI"}), 1000);
})
});

This way, when a client connects and sends a ' Foo ' event to the server, we send some information to it every 1 seconds.

After the client, establish the connection as follows:

Import io from ' socket.io-client ';

var socket = new Io ("http://localhost:3000");
Socket.on (' Connect ', () =>{
Console.log ("connected!");
})

Socket.on (' Disconnect ', () =>{
Console.log ("disconnected!");
})

Then send and accept events from the server just now.

Socket.emit ("foo", {});

Socket.on ("Bar", data=>{
Console.log ("Rec:", data);
})

You can see in the console in chrome that every second of the Web is receiving information from the server, but WebSocket seems to support it on other browsers.

TCG Development Log (3) Socket.io

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.