1. Create a project, the folder, where you use Testsocket
2. Create file Package.json to describe the project:
{
"Name": "Testsocket",
"Version": "0.0.1",
"description": "My first Nodejs app",
"Dependencies": {
"Express": "~4.10.2",,
"Socket.io": "~1.2.0"
}
}
3. Create Index.js
var app = require (' Express ') ();
Express initialize variable app as a method for HTTP service
var http = require (' http '). Server (APP);
var io = require (' Socket.io ') (HTTP);
Define a routing method '/' as the return result of our visit to the homepage of the site
App.get ('/', function (req, res) {
Res.sendfile (__dirname + '/index.html ');
Console.log (' New link: ', req);
});
Io.on (' Connection ', function (socket) {
Socket.on (' Chat message ', function (msg) {
Io.emit (' Chat message ', msg);
Console.log (' message: ' + msg);
});
});
Listening to server 3000 ports
Http.listen (, function () {
Console.log (' listening on *:3000 ');
});
4. Create index.html
<!doctype html>
<title>socket.io chat</title>
<style>
* {margin:0; padding:0; box-sizing:border-box;}
Body {font:13px Helvetica, Arial;}
form {background: #000; padding:3px; position:fixed; bottom:0; width:100%;}
form input {border:0; padding:10px; width:90%; Margin-right:. 5%;}
Form button {width:9%; Background:rgb (224, 255); border:none; padding:10px;}
#messages {list-style-type:none; margin:0; padding:0;}
#messages li {padding:5px 10px;}
#messages Li:nth-child (odd) {background: #eee;}
</style>
<body>
<ul id= "Messages" ></ul>
<form action= "" >
<input id= "M" autocomplete= "Off"/><button>send</button>
</form>
<script src= "Https://cdn.socket.io/socket.io-1.2.0.js" ></script>
<script src= "Http://code.jquery.com/jquery-1.11.1.js" ></script>
<script>
var myID = Math.floor (Math.random () * 100) + 1;
var socket = io ('/');
$ (' form '). Submit (function () {
Socket.emit (' Chat message ', myID + ' says: ' + $ (' #m '). Val ());
$ (' #m '). Val (');
return false;
});
Socket.on (' Chat message ', function (msg) {
$ (' #messages '). Append ($ (' <li> '). Text (msg));
});
</script>
</body>
5. Implementation
Installation:
NPM Install–save Express
NPM Install–save Socket.io
Node Index.js
Access 127.0.0.1:3000 in the browser
6. Implement these functions first, say something else.
"Socket.io Study" 2. Small test sledgehammer