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

  • 1828
  • 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 

https://socket.io/docs/#how-to-use

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 socket.io     to install socket.io

 

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('socket.io')(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) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

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

 

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



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

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

 

7. use cmd execute command node app.js  to run the server.

 

8.open 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:

https://stackoverflow.com/questions/17757728/where-is-the-socket-io-client-side-js-file-located