The socket. Io official website uses express to implement the simplest im instant chat. Today we use Koa to implement it.
### Framework preparation
- Make sure that you have installed nodejs and NPM locally. Use Koa to require node version> 7.6
- Create a folder (the official website name is chat-example) where you need it)
- Go to the project directory and create the package. JSON file:
{ "name": "socket-chat-example", "version": "0.0.1", "description": "my first socket.io app", "dependencies": {}}
4. Run the following command to install NPM in the command line:
npm install --save koa koa-router http fs socket.io
### Add the Code directly next
Directly create index. js under the project directory
VaR Koa = require ('koa'); var APP = new Koa (); const router = require ('koa-router '); const FS = require ('fs '); const Server = require ('HTTP '). createserver (App. callback (); const IO = require ('socket. io ') (server); // home page route let router = new router (); router. get ('/', CTX => {CTX. response. type = 'html '; CTX. response. body = FS. createreadstream ('. /index.html ');}); app. use (router. routes (); // socket connection Io. on ('connection', (socket) => {socket. on ('chat message', (MSG) => {console. log ('message: '+ MSG); Io. emit ('chat message', MSG) ;}); socket. on ('disconnect', () => {console. log ('user disconnected') ;}); // listening port server. listen (3000, () => {console. log ('listening on *: 100 ');});
Important:
- The socket connection method is to first establish a server, and its access method is no longer:
VaR HTTP = require ('http'). Server (APP );
VaR IO = require ('socket. Io ') (HTTP );
But it becomes:
Const Server = require ('HTTP '). createserver (App. Callback ());
Const IO = require ('socket. Io ') (server );
- After node8, function () {} can be simplified to () =>{}, which is more concise in writing.
Page index.html
<!doctype html>
Like the official website, index.html is not modified.
Finally, execute node index. JS, open the browser, and enter http: // localhost: 3000 to implement the simplest chat. How to Use Koa to implement socket. Io official website examples