NodeJS的socket通信

前段时间就开始学习NodeJS了,只是没有真正的实战,这几天一直在玩NodeJS的Socket通信,真是难搞啊,玩了两天,终于可以了,可能也是版本库没有升级到对应的版本的问题,重新npm安装后也就可以了,蛋疼,接下来贴一下网上整理的代码(自己通过测试的),在运行以下NodeJS实例前你必须装好NodeJS服务器,

客户端HTML如下:

<!DOCTYPE html>
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <button id="send">发送消息</button>
<script src="jquery.js"></script>
<script src="http://localhost:8082/socket.io/socket.io.js"></script>
<script>
var browserType, browserVersion, ua=navigator.userAgent.toLowerCase();  
if (ua.match(/msie/) != null || ua.match(/trident/) != null) {  
    //浏览器类型  
    browserType = "ie";
    //浏览器版本  
    browserVersion = ua.match(/msie ([\d.]+)/) != null ? ua.match(/msie ([\d.]+)/)[1] : ua.match(/rv:([\d.]+)/)[1];
} else {
    if(/firefox/.test(navigator.userAgent.toLowerCase())){ browserType = "ff"; }

    if(/webkit/.test(navigator.userAgent.toLowerCase())){ browserType = "wk"; }

    if(/opera/.test(navigator.userAgent.toLowerCase())){ browserType = "op"; }
}

window.onload=function(){
    
    var url='127.0.0.1:8082';
    // Webkit
//    var socket = io.connect('localhost',{port:8082,rememberTransport:true,timeout:1500});

    var socket = new io.Socket(null,{port:8082,rememberTransport:true,timeout:1500});

    if (/Firefox\/\s/.test(navigator.userAgent)){
        var socket = io.connect(url,{transports:['xhr-polling']}); 
    } 
    else if (/MSIE (\d+.\d+);/.test(navigator.userAgent)){
        var socket = io.connect(url,{transports:['jsonp-polling']}); 
    } 
    else { 
        var socket = io.connect(url,{transports:['websocket']}); 
    }

//    socket.connect();
 
 
 
    socket.on('connect', function(){ 
        console.log('connected to server++++++++++++++++'); 
        socket.send('Hi Server...'); 
    }) ;
    socket.on('message', function(r){ console.log('msg:+++++++++++'+r); }) ;
    socket.on('disconnect', function(){ console.log('disconnected from server'); }) ;

    socket.on('news', function (data) {
        console.log("++++++++++++++++++++++++++");
        console.log(data);
        
        //发送自定义事件
        socket.emit('my other event', { my: browserType });
    });
    
    /*XMLHttpRequest cannot load http://localhost:8082/socket.io/1/?t=1336306289263. Origin null is not allowed by Access-Control-Allow-Origin.
    var ws = new WebSocket("ws://127.0.0.1:8082");
    ws.onopen = function(){console.log('connected to server');}
    ws.onmessage = function(m){console.log('onmessage');}
    ws.onclose = function(){}*/
    var sendMsg = function(data){
          socket.emit('myotherevent', { my: data });
    }
    document.querySelector('#send').addEventListener('click', function(){
          sendMsg(browserType);
    });
}
</script>
    </body>
</html>

Server的代码如下:

//原始Http请求方式
var http = require('http'),  
io = require('socket.io'),
sys = require('sys');

server = http.createServer(function(req, res){
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    res.end("hello");
});
server.listen(8082);

/*
//express发请求module
var express = require('express'),  
io = require('socket.io'),
sys = require('sys');

var app = express();
app.use(express.static(__dirname));
var server = app.listen(8082);
 */

var socket = io.listen(server,{origins: '*:*'}); 

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

    sys.puts("New client is here!");
    client.send("hello world");

    client.on('message', function(msg){ sys.puts("client has sent:"+msg); }) ;
    client.on('disconnect', function(){ sys.puts("Client has disconnected"); }) ;
    
    //发送自定义事件
    client.emit('news', { hello: 'news world' });

    //临听自定义事件
    client.on('myotherevent', function (data) {
        console.log(data);
        client.emit('news', 'server has receive the message!' + data.my);
//        client.broadcast.emit('news', 'server has receive the message!' + data.my);//广播方式
    });
});

效果自己测试即可看出来,在浏览器的的console和服务器可以看得到输出的内容。

Leave a comment