websocket试用

来源:互联网 发布:中国企业海外上市数据 编辑:程序博客网 时间:2024/05/22 06:15

websocket
1.通过websocket协议握手
2.后续通过tcp流方式交互

这个文章可以作为一个协议简介

在PC上试用,winxp,软件包选用了WebSocket-Node,websocket协议的nodejs扩展包

安装:
* npm install -g node-gyp
* npm install websocket

* server端代码(ws_demo_server.js)

半抄半改

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
"use strict";
 
// Optional. You will see this name in eg. 'ps' or 'top' command
process.title = 'node-chat';
 
// Port where we'll run the websocket server
var webSocketsServerPort = 9000;
 
// websocket and http servers
var webSocketServer = require('websocket').server;
var http = require('http');
 
/**
 * Global variables
 */
// latest 100 messages
var history = [ ];
// list of currently connected clients (users)
var clients = [ ];
 
/**
 * HTTP server
 */
var server = http.createServer(function(request, response) {
    // Not important for us. We're writing WebSocket server, not HTTP server
});
server.listen(webSocketsServerPort,function() {
    console.log((newDate()) + " Server is listening on port "+ webSocketsServerPort);
});
 
/**
 * WebSocket server
 */
var wsServer = new webSocketServer({
    // WebSocket server is tied to a HTTP server. WebSocket request is just
    // an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6
    httpServer: server,
    autoAcceptConnections:false
});
 
 
function msg_history(userName, friend, msg){
    varhistory = {
        type:'message',
        time: (newDate()).getTime(),
        msg: msg,
        user: userName,
        friend: friend,
    };
    returnhistory;
}
 
function reg_user(userName, host, port) {
  // put logic here to detect whether the specified origin is allowed.
  returntrue;
}
 
// This callback function is called every time someone
// tries to connect to the WebSocket server
wsServer.on('request',function(request) {
    console.log((newDate()) + ' Connection from origin '+ request.origin + '.');
 
    // accept connection - you should check 'request.origin' to make sure that
    // client is connecting from your website
    // (http://en.wikipedia.org/wiki/Same_origin_policy)
    varconnection = request.accept(null, request.origin);
    // we need to know client index to remove them on 'close' event
    varindex = clients.push(connection) - 1;
    varuserName = false;
 
    console.log((newDate()) + ' Connection accepted.');
 
    // send back chat history
    if(history.length > 0) {
        connection.sendUTF(JSON.stringify( { type:'history', data: history} ));
    }
 
    // user sent some message
    connection.on('message',function(message) {
        if(message.type === 'utf8') {// accept only text
            if(userName === false) {// first message sent by user is their name
             
                // remember user name
                varmsgObj = JSON.parse(message.utf8Data);
                userName = msgObj['data']['userName'];
                console.log((newDate()) + ' User : '+ userName );
 
                // get random color and send it back to the user
                varmsg = msg_history(userName, msgObj['data']['userFirend'], msgObj['data']['talkMsg']);
                connection.sendUTF(JSON.stringify(msg));
                 
            }else { // log and broadcast the message
                console.log((newDate()) + ' Received Message from '+ userName + ': ' + message.utf8Data);
 
                // we want to keep history of all sent messages
                varmsgObj = JSON.parse(message.utf8Data);
                varmsg = msg_history(msgObj['data']['userName'], msgObj['data']['userFirend'], msgObj['data']['talkMsg']);
                history.push(msg);
                history = history.slice(-100);
 
                // broadcast message to all connected clients
                varjson = JSON.stringify(msg);
                for(var i=0; i < clients.length; i++) {
                    clients[i].sendUTF(json);
                }
            }
        }elseif (message.type === 'binary') {
            console.log('Received Binary Message of '+ message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }else{
            console.log('Received Unknow Type Message');
            connection.sendBytes('Received Unknow Type Message');
        }
    });
 
    // user disconnected
    connection.on('close',function(connection) {
        if(userName !== false) {
            console.log((newDate()) + " Peer "
                + connection.remoteAddress +" disconnected.");
            // remove user from the list of connected clients
            clients.splice(index, 1);
            // push back user's color to be reused by another user
        }
    });
 
});




* clien端代码(ws_demo_client.html)

(也是半抄半改,chrom下OK,测试要多开几个页面)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<html>
<head>
<script type="text/javascript">
var host = '127.0.0.1';
var port = 9000;
var url = 'ws://'+host+':'+port+'/';
 
var w = new WebSocket(url);
 
w.onopen = function(){
    $('stat-box').innerHTML ='已连接到服务器......<br/>';
}
 
function json2str(json){
    returnJSON.stringify(json)
}
 
function str2json(str){
    returnJSON.parse(str);
}
 
w.onmessage = function(e){
    varobj = str2json(e.data);
    varchatBox = $('chat-box');
 
    if(typeof(obj.type) == undefined) {
         
    }else if (obj.type == 'history')  {
        for(varidx in obj.data){
            vartime = Math.round(obj.data[idx]['time'] / 1000);
            varfromWho = obj.data[idx]['user'];
            vartoWho = ( "" == obj.data[idx]['friend'] ) ?"所有人" : obj.data[idx]['friend'];
            varmsg = obj.data[idx]['msg'];
            chatBox.innerHTML = chatBox.innerHTML + time +':<br/> ' + fromWho +" 对 " + toWho + " 说:" + msg + '<br/>';
        }
    }else if (obj.type == 'message') {
        vartime = Math.round(obj['time'] / 1000);
        varfromWho = obj['user'];
        vartoWho = ( "" == obj['friend'] ) ?"所有人" : obj['friend'];
        varmsg = obj['msg'];
        chatBox.innerHTML = chatBox.innerHTML + time +':<br/> ' + fromWho +" 对 " + toWho + " 说:" + msg + '<br/>';
    }
}
 
function send(){
    varuserName = $('userName');
    varuserFirend = $('userFirend');
    vartalkMsg = $('talkMsg');
     
    varmsgToSend={"data":{"userName":userName.value,"userFirend":userFirend.value,"talkMsg":talkMsg.value}};
    w.send(json2str(msgToSend));
}
function $(id){
    returndocument.getElementById(id);
}
</script>
</head>
 
<body>
<div id="chat-box"style="bordddder:1px solid #cccccc; width:400px; height:400px; overflow:scroll;"></div>
<div id="stat-box"style="bordddder:1px solid #cccccc;"></div>
昵称    :<input type="text"id="userName"/><br/>
发给朋友:<input type="text"id="userFirend"/><br/>
内容    :<input type="text"id="talkMsg"/><br/>
<input type="button"id="send" onClick="send();" value="发送"/>
</body>
</html>
0 0