Socket.IO 教學 基礎範例 Socket.IO Tutorial Basic Example

  • 1974
  • 0
  • 2018-06-29

Socket.IO 教學 基礎範例 Socket.IO  Tutorial  Basic Example

Here I show an example in Official Socket.IO Doc, the Doc link is

And here using Windows system:


1. Create a folder in your computer, for example  D:\App ,

2. Open cmd and change directory to this folder.

3. use command:  npm install     to install


4. In the official doc example, its Server (app.js)  and  Client (index.html) are using default 80 port,

but sometimes 80 port will conflict with other app,

so here I show how to use custom port,  I use port 2341 for example.


5. Create file app.js in the folder in point 1,    with content below:

var app = require('http').createServer(handler)
var io = require('')(app);
var fs = require('fs');

app.listen(2341);    //use port 2341

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      return res.end('Error loading index.html');


io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {


6. Create file index.html in the folder in point 1,    with content below:

<!-- in src use 2341 as port to get the -->
<script src="http://localhost:2341/"></script>

  <!-- connect to localhost 2341   -->
  var socket = io('http://localhost:2341');
  socket.on('news', function (data) {
    socket.emit('my other event', { my: 'data' });


7. use cmd execute command node app.js  to run the server. the index.html in browser, the script will be execute and connect to server http://localhost:2341,

then through the definition emit and on  in server script and client script, the mesaage can be send and accept.


9. The result:

In the browser like chrome, press F12  to open the developer tool,  and you can see the console.log print hello : "world"


And in the cmd you can see it print my : 'data'


Some referenece: