How to get the responses from websocket server to client(socket.io) using nodejs

落花浮王杯 提交于 2020-01-16 07:53:08

问题


I included the socket.io.js in client and also included the custom created socket.js for getting the responses from websocket server to client,when i loading this page in browser automatically stopped the websocket server and in browser console tells WebSocket connection to 'ws://localhost:8000/socket.io/?EIO=3&transport=websocket&sid=2p1ZYDAflHMHiL70AAAA' failed: Connection closed before receiving a handshake response user defined socket.js code is given below

var socket = io();
var actionItems = []
var beginTakingAction = false

var strOut;
socket.on('transcript', function(x) {
var div = $('div.transcription')
div.html(x);
console.log("transcript " + x);
if (!scrolling) {
  div.scrollTop(div[0].scrollHeight);
}   
})

socket.on('action', function(x) {
  console.log('sending action',x);
  actionItems.push(x)
  $('div.action').html(actionItems[actionItems.length-1]);

})
socket.on('sentiment', function(x) {
sentimentChart.update(x)
})

socket.on('nlp', function(x) {
wordLengthDistChart.update(x.wordLenghDist);
posTagDistChart.update(x.posTagDist);
})

socket.on('keywords', function(x) {
keywordChart.update(x)
})

socket.on('status', function(status) {
$('div.status').html("status: " + status);

if (status == "connected") {
  sentimentChart.reset()
  keywordChart.reset()
  wordLengthDistChart.reset()
  posTagDistChart.reset()
  $('div.transcription').html('');
}

})

please give any suggesstions??

my server code is given below

require('dotenv').config()

var WebSocketServer = require('websocket').server;

var http = require('http');
var HttpDispatcher = require('httpdispatcher');
var dispatcher     = new HttpDispatcher();
const fs = require('fs');
const winston = require('winston')
winston.level = process.env.LOG_LEVEL || 'info'

var AsrClient = require('./lib/asrClient')
var asrActive = false
var myAsrClient;
var engineStartedMs;
var connections = []
//Create a server
var server = http.createServer(function(req, res) {
  handleRequest(req,res);
});

// Loading socket.io
var io = require('socket.io').listen(server);

// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
 winston.log('info','A client is connected!');
});


var wsServer = new WebSocketServer({
   httpServer: server,
   autoAcceptConnections: true,
   binaryType: 'arraybuffer'
});


 //Lets use our dispatcher
 function handleRequest(request, response){
    try {
        //log the request on console
        winston.log('info', 'handleRequest',request.url);
        //Dispatch
         dispatcher.dispatch(request, response);
     } catch(err) {
       console.log(err);
    }
  }
       dispatcher.setStatic('/public');
    dispatcher.setStaticDirname('public');
    dispatcher.onGet("/", function(req, res) {
      winston.log('info', 'loading index');
      winston.log('info', 'port', process.env.PORT)
       fs.readFile('./public/index.html', 'utf-8', function(error, content) {
            winston.log('debug', 'loading Index');
            res.writeHead(200, {"Content-Type": "text/html"});
            res.end(content);
        });
    });
    // Serve the ncco
    dispatcher.onGet("/ncco", function(req, res) {
        fs.readFile('./ncco.json', function(error, data) {
            winston.log('debug', 'loading ncco');
           res.writeHead(200, { 'Content-Type': 'application/json' });
           res.end(data, 'utf-8');
        });
    });

    dispatcher.onPost("/terminate", function(req, res) {
         winston.log('info', 'terminate called');
         wsServer.closeAllConnections();

        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end();
    });

    wsServer.on('connect', function(connection) {
        connections.push(connection);

        winston.log('info', (new Date()) + ' Connection accepted' + ' - Protocol Version ' + connection.webSocketVersion);
        connection.on('message', function(message) {

            if (message.type === 'utf8') {
                try {
                  var json = JSON.parse(message.utf8Data);
                  winston.log('info', "json", json['app']);

                  if (json['app'] == "audiosocket") {
                    VBConnect();
                    winston.log('info', 'connecting to VB');
                  }

                } catch (e) {
                  winston.log('error', 'message error catch', e)
                }
                winston.log('info', "utf ",message.utf8Data);
            }
            else if (message.type === 'binary') {
                // Reflect the message back
                // connection.sendBytes(message.binaryData);
                if (myAsrClient != null && asrActive) {  
                  winston.log('debug', "sendingDate ",message.binaryData);
                  myAsrClient.sendData(message.binaryData)
                }
            }
        });

        connection.on('close', function(reasonCode, description) {
            winston.log('info', (new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
            wsServer.closeAllConnections();

        });
    });

    wsServer.on('close', function(connection) {
      winston.log('info', 'socket closed');
      if (asrActive) {
          io.sockets.emit('status',  "disconnected");
          winston.log('info', 'trying to close ASR client');
          myAsrClient.close();
          myAsrClient = null;
          asrActive = false;
      }
      else {
        winston.log('info', 'asr not active, cant close');
      }
    })

    wsServer.on('error', function(error) {
      winston.log('error', 'Websocket error', error);
    })

    var port = process.env.PORT || 8000
    server.listen(port, function(){
        winston.log('info', "Server listening on :%s", port);
    });

来源:https://stackoverflow.com/questions/48781185/how-to-get-the-responses-from-websocket-server-to-clientsocket-io-using-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!