【轉】windows下使用WebSocket-Node搭建WebSocket伺服器
阿新 • • 發佈:2019-02-03
第一步:安裝好node.js和npm
這個就不贅述了.
在dos命令下測試
第二步:安裝WebSocket-Node模組
Node.js command prompt輸入命令
npm install websocket
記住,不要全域性安裝,不然後續呼叫模組的時候會報類似的Error: Cannot find module 'websocket'
錯.
第三步:windows下安裝Microsoft Visual C++和Python 2.7
(windows下面才需要安裝..)一般情況下windows下都會安裝有Microsoft Visual C++,所以我們需要繼續安裝 Python 2.7.10
下載
第四步:測試WebSocket伺服器
建立ws.js檔案
輸入程式碼(直接從WebSocket-Node模組裡面拷貝下來的)
[javascript] view plain copy
- #!/usr/bin/env node
- var WebSocketServer = require('websocket').server;
- var http = require('http');
- var server = http.createServer(function(request, response) {
- console.log((new
- response.writeHead(404);
- response.end();
- });
- server.listen(8080, function() {
- console.log((new Date()) + ' Server is listening on port 8080');
- });
- wsServer = new WebSocketServer({
- httpServer: server,
- // You should not use autoAcceptConnections for production
- // applications, as it defeats all standard cross-origin protection
- // facilities built into the protocol and the browser. You should
- // *always* verify the connection's origin and decide whether or not
- // to accept it.
- autoAcceptConnections: false
- });
- function originIsAllowed(origin) {
- // put logic here to detect whether the specified origin is allowed.
- return true;
- }
- wsServer.on('request', function(request) {
- if (!originIsAllowed(request.origin)) {
- // Make sure we only accept requests from an allowed origin
- request.reject();
- console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
- return;
- }
- var connection = request.accept('echo-protocol', request.origin);
- console.log((new Date()) + ' Connection accepted.');
- connection.on('message', function(message) {
- if (message.type === 'utf8') {
- console.log('Received Message: ' + message.utf8Data);
- connection.sendUTF(message.utf8Data);
- }
- else if (message.type === 'binary') {
- console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
- connection.sendBytes(message.binaryData);
- }
- });
- connection.on('close', function(reasonCode, description) {
- console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
- });
- });
Node.js command promp命令cd到你建立的js檔案所在目錄下面.執行
node ws.js
結果如圖
使用chrome瀏覽器測試
新建一個html檔案
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Document</title>
- </head>
- <body>
- <button type="button" id="start" onclick="start()">start</button>
- <script>
- function start(){
- var client = new WebSocket('ws://localhost:8080/', 'echo-protocol');
- client.onerror = function() {
- console.log('Connection Error');
- };
- client.onopen = function() {
- console.log('WebSocket Client Connected');
- function sendNumber() {
- if (client.readyState === client.OPEN) {
- var number = Math.round(Math.random() * 0xFFFFFF);
- client.send(number.toString());
- setTimeout(sendNumber, 1000);
- }
- }
- sendNumber();
- };
- client.onclose = function() {
- console.log('echo-protocol Client Closed');
- };
- client.onmessage = function(e) {
- if (typeof e.data === 'string') {
- console.log("Received: '" + e.data + "'");
- }
- };
- }
- </script>
- </body>
- </html>