• socket.io


    http://www.2cto.com/kf/201403/285640.html

    server.js

     1 var io = require('socket.io').listen(8080);
     2 io.set('log level', 1);
     3 var users = {};
     4 io.sockets.on('connection', function (socket) {
     5   io.sockets.emit('connect',{hell:'boy'});
     6  
     7   socket.on('private message', function (from,to,msg) {
     8     console.log('I received a private message by ', from, ' say to ',to, msg);
     9     if(to in users){
    10         users[to].emit('to'+to,{mess:msg});
    11     }
    12   });
    13   socket.on('new user',function(data){
    14      if(data in users){
    15          
    16      }else{
    17         var nickname = data;
    18         users[nickname]= socket;
    19      }
    20      console.info(users);
    21   });
    22   socket.on('disconnect', function () {
    23     io.sockets.emit('user disconnected');
    24   });
    25 });

    测试页面index.html

     1 <meta charset="utf-8">
     2     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
     3     <script src="http://localhost:8080/socket.io/socket.io.js"></script>
     4     <script>
     5         $(function(){
     6             var socket = io.connect('http://localhost:8080');
     7             socket.on('connect', function (data) {
     8                 console.log(data);  
     9             });
    10              $("#send").click(function(e){
    11                 var from = $('#user_name').val(),
    12                     msg  = $('#message').val(),
    13                     to   = $('#to').val(),
    14                  $message_list = $('#message_list');
    15                  socket.emit('new user',from);
    16                  socket.emit('private message',from,to,msg);
    17                  socket.on('to'+from, function (data) {
    18                     $message_list.append('<li>'+data.from+''+data.message+'</li><li>');
    19                 });
    20              });
    21         });
    22     </script>
    23  
    24  
    25     姓名:<input id="user_name" type="text"><br>
    26     发送给:<input type="text" id="to"><br>
    27     消息内容:<input type="text" id="message"><button type="button" id="send">发送</button>
    28     <ul id="message_list">
    29          
    30     </ul>
    31  
    32  
    33 </li>
  • 相关阅读:
    AJAX以及XMLHttpRequest
    理解Promise对象
    HTTP报文整理
    前端 — URL、URI、URN概念和区别整理,以及URL语法规则
    gulp与webpack的区别
    Sass和less的区别是什么?用哪个好
    Vue3.0 && Vue3.0初体验 一
    Promise入门详解和基本用法
    js对象方法大全
    hash模式和history模式 实现原理及区别
  • 原文地址:https://www.cnblogs.com/labihua/p/4547544.html
Copyright © 2020-2023  润新知