node学习笔记之io.sockets

 socket.get和socket.set函数已经失效,代码修改如下所示:

 

服务器端:

var httpd = require('http').createServer(handler);
var io = require('socket.io').listen(httpd);
var fs = require('fs');

httpd.listen(3000);

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.sockets.on('connection', function (socket) {
  socket.on('clientMessage', function(content) {
    socket.emit('serverMessage', 'You said: ' + content);
    var username = null;

    if (socket.username) {
        username = socket.username;
    }
      socket.broadcast.emit('serverMessage', username + ' said: ' + 
        content);
  });

  socket.on('login', function(username) {
    socket.username = username;
    socket.emit('serverMessage', 'Currently logged in as ' + username);
    socket.broadcast.emit('serverMessage', 'User ' + username +
      ' logged in');   
  });

  socket.emit('login');

});

客户端:

<html>
  <head>
    <title>Node.js WebSocket chat</title>
    <style type="text/css">
      #input {
        width: 200px;
      }
      #messages {
        position: fixed;
        top: 40px;
        bottom: 8px;
        left: 8px;
        right: 8px;
        border: 1px solid #EEEEEE;
        padding: 8px;
      }
    </style>
  </head>

  <body>

    Your message:
    <input type="text" id="input">

    <div id="messages"></div>

    <script src="http://localhost:3000/socket.io/socket.io.js"></script>
    <script type="text/javascript">
      var messagesElement = document.getElementById('messages');
      var lastMessageElement = null;

      function addMessage(message) {
        var newMessageElement = document.createElement('div');
        var newMessageText = document.createTextNode(message);

        newMessageElement.appendChild(newMessageText);
        messagesElement.insertBefore(newMessageElement, 
          lastMessageElement);
        lastMessageElement = newMessageElement;
      }

      var socket = io.connect('http://localhost:3000');
      socket.on('serverMessage', function(content) {
        addMessage(content);
      });

      socket.on('login', function() {
        var username = prompt('What username would you like to use?');
        socket.emit('login', username);
      });

      var inputElement = document.getElementById('input');

      inputElement.onkeydown = function(keyboardEvent) {
        if (keyboardEvent.keyCode === 13) {
          socket.emit('clientMessage', inputElement.value);
          inputElement.value = '';
          return false;
        } else {
          return true;
        }
      };
    </script>

  </body>
</html>

 

posted @ 2019-01-25 18:36  小猪冒泡  阅读(673)  评论(0编辑  收藏  举报