webSocket websoket使用Protocol Buffers3.0傳輸

首先安裝node。html

而後node

npm install ws

ws是webSocket模塊。web

而後建立一個sever.js文件,在裏面新建一個服務npm

var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({ port: 8181 });
wss.on('connection', function (ws) {
    console.log('client connected');
    ws.on('message', function (message) {
        console.log(message);
    });
});

以後就是頁面了,index.html,在頁面中建立一個鏈接app

 var ws = new WebSocket("ws://localhost:8181");
    ws.onopen = function (e) {
        console.log('Connection to server opened');
    }
    function sendMessage() {
        ws.send($('#message').val());
    }

使用send方法發送數據。socket

 

一個實時聊天的例子                                                                                    post

1.安裝node-uuid模塊,用來給每一個鏈接一個惟一號。學習

2.服務端消息發送ui

 

消息類型分notification和message兩種,前者是提示信息,後者是聊天內容。消息還包含一個id、暱稱和消息內容。在上一節有學習到readyState有四個值,OPEN表示鏈接創建能夠發送消息。若是頁面關閉了,爲WebSocket.CLOSE。url

 

function wsSend(type, client_uuid, nickname, message) {
    for (var i = 0; i < clients.length; i++) {
        var clientSocket = clients[i].ws;
        if (clientSocket.readyState === WebSocket.OPEN) {
            clientSocket.send(JSON.stringify({
                "type": type,
                "id": client_uuid,
                "nickname": nickname,
                "message": message
            }));
        }
    }
}

3.服務端處理鏈接

每新增長一個鏈接,都會發送一條匿名用戶的加入的提示消息,若是消息中帶有「/nick」 認爲這一個修改暱稱的消息。而後更新客戶端的暱稱。其餘都會當作聊天消息處理。

wss.on('connection', function(ws) {
    var client_uuid = uuid.v4();
    var nickname = "AnonymousUser" + clientIndex;
    clientIndex += 1;
    clients.push({ "id": client_uuid, "ws": ws, "nickname": nickname });
    console.log('client [%s] connected', client_uuid);
    var connect_message = nickname + " has connected";
    wsSend("notification", client_uuid, nickname, connect_message);
    console.log('client [%s] connected', client_uuid);
    ws.on('message', function(message) {
        if (message.indexOf('/nick') === 0) {
            var nickname_array = message.split(' ');
            if (nickname_array.length >= 2) {
                var old_nickname = nickname;
                nickname = nickname_array[1];
                var nickname_message = "Client " + old_nickname + " changed to " + nickname;
                wsSend("nick_update", client_uuid, nickname, nickname_message);
            }
        } else {
            wsSend("message", client_uuid, nickname, message);
        }
    });

 

處理鏈接關閉:

 var closeSocket = function(customMessage) {
        for (var i = 0; i < clients.length; i++) {
            if (clients[i].id == client_uuid) {
                var disconnect_message;
                if (customMessage) {
                    disconnect_message = customMessage;
                } else {
                    disconnect_message = nickname + " has disconnected";
                }
                wsSend("notification", client_uuid, nickname, disconnect_message);
                clients.splice(i, 1);
            }
        }
    };
    ws.on('close', function () {
        closeSocket();
    });

 

4.客戶端

 沒有啓動時,頁面以下,change按鈕用來修改暱稱。

js:

   //創建鏈接
        var ws = new WebSocket("ws://localhost:8181");
        var nickname = "";
        ws.onopen = function (e) {
            console.log('Connection to server opened');
        }
        //顯示
        function appendLog(type, nickname, message) {
            if (typeof message == "undefined") return;
            var messages = document.getElementById('messages');
            var messageElem = document.createElement("li");
            var preface_label;
            if (type === 'notification') {
                preface_label = "<span class=\"label label-info\">*</span>";
            } else if (type == 'nick_update') {
                preface_label = "<span class=\"label label-warning\">*</span>";
            } else {
                preface_label = "<span class=\"label label-success\">"
                + nickname + "</span>";
            }
            var message_text = "<h2>" + preface_label + "&nbsp;&nbsp;"
            + message + "</h2>";
            messageElem.innerHTML = message_text;
            messages.appendChild(messageElem);
        }
        //收到消息處理
        ws.onmessage = function (e) {
            var data = JSON.parse(e.data);
            nickname = data.nickname;
            appendLog(data.type, data.nickname, data.message);
            console.log("ID: [%s] = %s", data.id, data.message);
        }
        ws.onclose = function (e) {
            appendLog("Connection closed");
            console.log("Connection closed");
        }
        //發送消息
        function sendMessage() {
            var messageField = document.getElementById('message');
            if (ws.readyState === WebSocket.OPEN) {
                ws.send(messageField.value);
            }
            messageField.value = '';
            messageField.focus();
        }
        //修更名稱
        function changName() {
            var name = $("#name").val();
            if (ws.readyState === WebSocket.OPEN) {
                ws.send("/nick " + name);
            }
        }

 

 源碼:http://pan.baidu.com/s/1c2FfKbA

 源碼:http://pan.baidu.com/s/1o8KRmUQ  加入了socket.io的實現。

 API:WebSocket API

 相關:websoket使用Protocol Buffers3.0傳輸

相關文章
相關標籤/搜索