websock(AMQ)通訊-前端

DanielDemi發表於2019-02-16

服務端和客戶端之間的通訊

前端開發經常會依賴後端,那麼如果後端伺服器還沒做好推送伺服器,那麼前端該如何呢。
最簡單的就是自己模擬一個伺服器,用node來搭建,這邊只簡單介紹搭建的過程

node搭建伺服器

1.選取websocket外掛進行開發

按照如下步驟進行開發
在命令臺中輸入以下命令

npm init -y 
npm i websocket -S

安裝完websocket外掛後就可以搭建伺服器了,首先新建一個app.js,並且程式碼如下

var webSocketsServerPort = 3002
var webSocketServer = require(`websocket`).server
var http = require(`http`)

var server = http.createServer(function(req, res) {

})
server.listen(webSocketsServerPort, function() {
    console.log((new Date()) + "Server is listening on port " + webSocketsServerPort)
})

/**
 * websock server
 */
var wsServer = new webSocketServer({
    httpServer: server
})

wsServer.on(`request`, function(request) {
    var connection = request.accept(null, request.origin); 
    connection.on(`message`, function(message) {
        console.log(`message`);
    });

    connection.on(`close`, function(connection) {
        console.log(`close`);
    });

})

這樣一個簡易的伺服器已經搭建完成。可以通過客戶端進行測試(客戶端程式碼見後面)

2.選取faye-websocket外掛進行開發

在命令臺中輸入以下命令

npm init -y 
npm i faye-websocket-S

這種方式更簡單了。程式碼如下

var WebSocket = require(`faye-websocket`),
    http      = require(`http`);

var server = http.createServer();

server.on(`upgrade`, function(request, socket, body) {
  if (WebSocket.isWebSocket(request)) {
    var ws = new WebSocket(request, socket, body);

    ws.on(`message`, function(event) {
      ws.send(event.data);
    });

    ws.on(`close`, function(event) {
      console.log(`close`, event.code, event.reason);
      ws = null;
    });
  }
});

server.listen(3002);
3.選取socket.io外掛進行開發

該外掛依賴於express
命令如下

express -e node-js-socketio // express模板安裝
npm i // 安裝express外掛
npm i socket.io -S // 安裝socket.io

app.js檔案改成如下程式碼

var app = require(`express`)()
  , server = require(`http`).createServer(app)
  , io = require(`socket.io`).listen(server);

server.listen(3002);

app.get(`/`, function (req, res) {
  res.sendfile(__dirname + `/client/index.html`);
});

io.sockets.on(`connection`, function (socket) {
  socket.emit(`news`, { hello: `world` });
  socket.on(`my other event`, function (data) {
    console.log(data);
  });
});

至此 伺服器搭建已經完成(還有一種是基於stomp.js,目前還沒弄清楚node如何搭建,等知道後在補充)

客戶端(即瀏覽器)呼叫伺服器

1.簡單的demo如下
<html>

<body>
    <div id="output"></div>
    <script>
    function checkBrowser() {
        if (window.WebSocket) {
            log("This browser supports WebSocket!");
        } else {
            log("This browser does not support WebSocket.");
        }
    }

    function setup() {
        var wsServer = `ws://localhost:3002`;
        var ws = new WebSocket(wsServer);

        ws.onopen = function(e) {
            log("Connected to WebSocket server.", e);
            sendMessage("Conan");
        };

        ws.onclose = function(e) {
            log("Disconnected", e);
        };

        ws.onmessage = function(e) {
            log("RECEIVED: " + e.data, e);
            ws.close();
        }

        ws.onerror = function(e) {
            log(`Error occured: ` + e.data, e);
        };

        var sendMessage = function(msg) {
            ws.send(msg);
            log("SEND : " + msg);
        }
    }

    function log(s, e) {
        var output = document.getElementById("output");
        var p = document.createElement("p");
        p.style.wordWrap = "break-word";
        p.style.padding = "10px";
        p.style.background = "#eee";
        p.textContent = "LOG : " + s;
        output.appendChild(p);
        console.log("LOG : " + s, e);
    }

    checkBrowser();
    setup();
    </script>
</body>

</html>
2.基於express的socket.io的demo如下
<!DOCTYPE html>
<html>
<head>
<title>socket.io</title>
</head>
<body>
<h1>socket.io</h1>
<p>Welcome to socket.io</p>

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script>
var socket = io.connect(`http://localhost:3002`);
socket.on(`news`, function (data) {
console.log(data);
socket.emit(`my other event`, { my: `data` });
});
</script>
</body>
</html>

3 基於AMQ的demo(目前還不知道伺服器如何搭建,但客戶端還是可以用的)

demo裡放了3種模式,主要就是Queue和topic,消費和釋出
Queue和topic的區別是一對多和多對多(QUEUE傳送一個人訊息之後,就消失了,而topic可以傳送多個人)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

    <script type="stompjs"></script>
    <script type="text/javascript">
    // 3種模式   
    // QUeue是隻有1對多模式,,topic多對多模式
    // 1.訊息釋出者模式
    var client = Stomp.overTCP(`localhost`, 61613);
    // uncomment to print out the STOMP frames

    var connectCallback = function(frame) {
        var subscription = client.subscribe(`/topic/FirstQueue`, onMessage);
        //subscription.unsubscribe();
    };

    var onMessage = function(message){
        if (message.body) {
          console.log("got message with body " + message.body)
        } else {
          console.log("got empty message");
        }
    };

    var errorCallback = function(error){
        console.log(error.headers.message);
    };

    client.connect(`admin`, `admin`, connectCallback,errorCallback);

    // 2.Queue訊息消費者
    var Stomp = require(`stompjs`);

    // Use raw TCP sockets
    var client = Stomp.overTCP(`localhost`, 61613);
    // uncomment to print out the STOMP frames
    // client.debug = console.log;

    var connectCallback = function(frame) {
        var subscription = client.subscribe(`/queue/FirstQueue`, onMessage);
        //subscription.unsubscribe();
    };

    var onMessage = function(message){
        if (message.body) {
          console.log("got message with body " + message.body)
        } else {
          console.log("got empty message");
        }
    };

    var errorCallback = function(error){
        console.log(error.headers.message);
    };

    client.connect(`admin`, `admin`, connectCallback,errorCallback);
    // 3.topic 訊息訂閱者模式
    // Use raw TCP sockets
    var client = Stomp.overTCP(`localhost`, 61613);
    // uncomment to print out the STOMP frames
    // client.debug = console.log;

    var connectCallback = function(frame) {
        var subscription = client.subscribe(`/topic/FirstQueue`, onMessage);
        //subscription.unsubscribe();
    };

    var onMessage = function(message){
        if (message.body) {
          console.log("got message with body " + message.body)
        } else {
          console.log("got empty message");
        }
    };

    var errorCallback = function(error){
        console.log(error.headers.message);
    };

    client.connect(`admin`, `admin`, connectCallback,errorCallback);
    </script>
</body>
</html>

相關文章