你的位置:首页 > Java教程

[Java教程]9.nodejs权威指南


1. Socket.IO

1.1 服务器

var http = require('http');

var sio = require('socket.io');

var fs = require('fs');

var server = http.createServer(function(req,rsp){

      rsp.writeHead(200,{'Content-Type':'text/html'});

      rsp.write('success');

});

server.listen(12345);

var socket = sio.listen(server);

socket.on('connection',function(client){

      client.send('from server');

      client.on('message',function(msg){

             console.log('from client' + msg);

      });

      socket.on('save data',function(data){

                   

      });

      socket.emit('my call back',{name:'chuck'});

      client.on('disconnect',function(){

            

      });

});

1.2 客户端

<!DOCTYPE html>

<html>

<head>

      <meta charset="UTF-8">

      <title>test</title>

      <script src="./socket.io.js"></script>

      <script>

             var socket = io.connect();

             socket.on('message',function(data){

                    socket.send('to server');

             });

             socket.on('disconnect',function(){

                   

             })

             socket.on('my call back',function(data){

                   

             });

             socket.emit('save data',{name:'chuck'});

      </script>

</head>

<body>

     

</body>

</html>