• nodejs server websocket


     1 var WebSocketServer = require('websocket').server;
     2 var http = require('http');
     3 
     4 var server = http.createServer(function(request, response) {
     5     console.log((new Date()) + ' Received request for ' + request.url);
     6     response.writeHead(404);
     7     response.end();
     8 });
     9 server.listen(8080, function() {
    10     console.log((new Date()) + ' Server is listening on port 8080');
    11 });
    12 
    13 wsServer = new WebSocketServer({
    14     httpServer: server,
    15     // You should not use autoAcceptConnections for production
    16     // applications, as it defeats all standard cross-origin protection
    17     // facilities built into the protocol and the browser.  You should
    18     // *always* verify the connection's origin and decide whether or not
    19     // to accept it.
    20     autoAcceptConnections: false
    21 });
    22 
    23 function originIsAllowed(origin) {
    24   // put logic here to detect whether the specified origin is allowed.
    25   return true;
    26 }
    27 
    28 wsServer.on('request', function(request) {
    29     if (!originIsAllowed(request.origin)) {
    30       // Make sure we only accept requests from an allowed origin
    31       request.reject();
    32       console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
    33       return;
    34     }
    35 
    36     var connection = request.accept('echo-protocol', request.origin);
    37     console.log((new Date()) + ' Connection accepted.');
    38     connection.on('message', function(message) {
    39         if (message.type === 'utf8') {
    40             console.log('Received Message: ' + message.utf8Data);
    41             connection.sendUTF(message.utf8Data);
    42         }
    43         else if (message.type === 'binary') {
    44             console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
    45             connection.sendBytes(message.binaryData);
    46         }
    47     });
    48     connection.on('close', function(reasonCode, description) {
    49         console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    50     });
    51 });
  • 相关阅读:
    Java MQTT 客户端之 Paho
    Spring Security + JJWT 实现 JWT 认证和授权
    MinIO
    Spring Boot 实现看门狗功能 (调用 Shell 脚本)
    Canal Admin
    canal
    浅尝 Elastic Stack (五) Logstash + Beats + Kafka
    养鸡场下蛋记
    涛声依旧
    原创:矩阵论学习心得
  • 原文地址:https://www.cnblogs.com/wblade/p/8570795.html
Copyright © 2020-2023  润新知