zoukankan      html  css  js  c++  java
  • socket.io笔记一

    //服务端代码
    var server = require('http').createServer(app);
    var io = require('socket.io')(server,{path:'/test',handshake:{xdomain:true}});
    io.on('connection', function(socket){ 
    	/* … */ 
    	console.log('连接OK')
    	socket.emit('online',{msg:'success'})
    });
    server.listen(3002);
    
    //客户端代码
    var ws = io('http://localhost:3002',{path:'/test'});
    ws.on('online',function(data){
    	console.log(data)
    })			
    //xdomain设置为true,代表连接允许跨域,否则当访问localhost/test的时候会报不允许跨域错误,这里是采取xhr长连接轮询的方式
    
    NOTE:当path设置'/test'的时候,socket连接会建立在localhost首页和localhost/test上,意思就是,如果首页和test页面都包含上面客户端的代码,访问这两个页面服务端的connection事件都会触发
    如果只允许当访问/test的时候才与服务端建立连接,去掉首页的客户端代码,或者通过url判断,例如:
    if(location.href === 'http://localhost:3002/test'){
      var ws = io('http://localhost:3002',{path:'/test'});
      ws.on('online',function(data){
        console.log(data)
      })
    }

     关于handshake的更多配置请看这里

      

  • 相关阅读:
    面试问题记录-C++
    面试问题记录-网络
    二叉树
    75. Sort Colors 荷兰国旗问题
    桶排序
    数据结构-堆
    快速排序
    第六章 数据库原理
    第五章 Java Web
    第四章 java基础知识
  • 原文地址:https://www.cnblogs.com/toward-the-sun/p/7134054.html
Copyright © 2011-2022 走看看