In my socket.onopen function there's a line that says socket.send(nickname), but for some reason I am getting an error - Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
Here's my code and screenshot of an error:
// создать подключение
var socket = null;
var nickname;
// отправить сообщение из формы publish
document.forms.publish.onsubmit = function() {
var outgoingMessage = this.message.value;
socket.send(outgoingMessage);
return false;
};
const connect = document.getElementById('connect');
const disconnect = document.getElementById('disconnect');
connect.addEventListener('click', function(){
start();
});
function start() {
socket = new WebSocket("ws://localhost:8081");
socket.onmessage = function(event) {
var incomingMessage = event.data;
showMessage(incomingMessage);
};
socket.onopen = authorizate();
}
function authorizate(){
nickname = document.getElementById('nickname').value;
document.getElementById('nickname').style.display = "none";
document.getElementById('subm').style.display = "inline-block";
disconnect.style.display = "inline-block";
connect.style.display = "none";
console.log(nickname);
socket.send(nickname);
}
Related
Im working on a voice recognition system where a voice command can pull up NASA's Astronomy Picture of the Day through their NASA API. I've made some simple code just to test it out by saying "Check Steve" and it'll check the check box named Steve. However when I say "Astronomy Picture of the Day", it returns "undefined" rather than the picture or text from the NASA API. Why is that?
var message = document.querySelector('#message');
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition;
var SpeechGrammarList = SpeechGrammarList || webkitSpeechGrammarList;
var grammar = '#JSGF V1.0;'
var recognition = new SpeechRecognition();
var speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
recognition.lang = 'en-US';
recognition.interimResults = false;
recognition.onspeechend = function() {
recognition.stop();
};
recognition.onerror = function(event) {
message.textContent = 'Error occurred in recognition: ' + event.error;
}
document.querySelector('#btnGiveCommand').addEventListener('click', function(){
recognition.start();
sendApiRequest()
});
async function sendApiRequest(){
let API_KEY = "7RTzkUMJOC8QYxM4COFoVha8NvAhxcZH2Ca7Px0G"
let response = await fetch(`https://api.nasa.gov/planetary/apod?api_key=${API_KEY}`);
console.log(response)
let event = await response.json()
console.log(event)
// how do i call the line of code right below this comment to this function?
}
recognition.onresult = function(event) {
var last = event.results.length - 1;
var command = event.results[last][0].transcript;
message.textContent = 'Voice Input: ' + command + '.';
if(command.toLowerCase() === 'astronomy picture of the day'){
document.querySelector("#chkSteve").innerHTML = event.explanation
}
else if (command.toLowerCase() === 'select tony'){
document.querySelector('#chkTony').checked = true;
}
else if (command.toLowerCase() === 'select bruce'){
document.querySelector('#chkBruce').checked = true;
}
else if (command.toLowerCase() === 'select nick'){
document.querySelector('#chkNick').checked = true;
}
}
The specific is this: I use java to read an audio file on the back end, and then transfer it to the front end of the web page through websocket. On the web page, I want to play the data received by the websocket through the Audio () object. I know that I know the SrcObject property used for specific playback, but I don't know how to implement it?
Below is the code of my web page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="send()">play</button>
</body>
</html>
<script>
var websocket = null;
//whether support or not WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/ws");
websocket.binaryType = "arraybuffer";
}
else {
alert('The current browser does not support websocket');
}
function send() {
websocket.send("play");
}
//
websocket.onmessage = function (event) {
var data = event.data;
// console.log(new Float32Array(data));
// play(data);
};
websocket.onopen = function () {
console.log("onopen...");
};
websocket.onclose = function () {
console.log("onclose...");
};
websocket.onerror = function () {
console.log("onerror...");
};
window.onbeforeunload = function () {
closeWebSocket();
};
function closeWebSocket() {
websocket.close();
}
var context;
var audio = new Audio();
var promise;
var flag = false;
var b = false;
var scriptProcessorNode;
var gainNode;
var streamAudioDestinationNode;
// data: arrayBuffer
function play(data) {
if (context === undefined) {
context = new AudioContext();
}
var buffer = context.createBuffer(2, 48000 * 2, 48000);
buffer.copyToChannel(new Float32Array(data), 1, 1);
var bufferSourceNode = context.createBufferSource();
bufferSourceNode.buffer = buffer;
if (!b) {
scriptProcessorNode = context.createScriptProcessor();
gainNode = context.createGain();
streamAudioDestinationNode = context.createMediaStreamDestination();
b = true;
}
bufferSourceNode.connect(scriptProcessorNode);
scriptProcessorNode.connect(gainNode);
gainNode.connect(streamAudioDestinationNode);
audio.srcObject = streamAudioDestinationNode.stream;
// audio.load();
if (!flag) {
promise = audio.play();
console.log("method play");
flag = true;
}
}
</script>
I have created WebSocket.js but unfortunately I am unable to test it due to unavailability of data. The requirement is the data comes from various sources so I have multiple sockets for that. Note: I want to particularly test my socket.onMessage behaves for different sockets. Please find the code snippet below:
var webSocket;
var txQueue = [];
var defaultReconnectTimeout = 1000; //will be multiplied by 2 and saved into reconnectTimeout on each try
var reconnectTimeout = defaultReconnectTimeout;
var registerWebSocketHandlers = function(webSocket) {
webSocket.onclose = function(){
setTimeout(service.reopen, reconnectTimeout *= 2);
};
webSocket.onopen = function(e) {
reconnectTimeout = defaultReconnectTimeout; //reset this
deferredSend();
};
webSocket.onerror = function(e) {
throw new Error("[WebSocket] An error occured " + e);
};
}
var uniqid = function() {
return (new Date().getTime()).toString(16);
}
var deferredSend = function() {
if(!service.isOpen()) {
$timeout(deferredSend, 100);
return;
}
while(txQueue.length && service.isOpen()) {
var payload = txQueue.shift();
webSocket.send(typeof payload === 'string' ? payload : JSON.stringify(payload));
}
};
var createNewWebSocketInstance = function(apiUrl){
var websocket = new $window.WebSocket(apiUrl);
websocket.id = uniqid();
return websocket;
}
// TODO: this is a bit hacky since we directly bind it to the raw window event
$window.onbeforeunload = function(e) {
service.close();
};
var service = {};
service.setMessageEventHandler = function(name,cb) {
instances[name].onmessage = function(msg) {
if(msg.data.indexOf('Status: connected') === 0)
{
return;
}
var jsonObj = JSON.parse(msg.data);
cb(jsonObj);
};
};
service.isOpen = function() {
return webSocket.readyState === 1;
};
service.send = function(msg) {
txQueue.push(msg);
deferredSend();
};
service.close = function() {
return webSocket.close();
};
service.reopen = function() {
// get old message handler
var msgHandler = webSocket.onmessage;
// try closing the previous WebSocket
service.close();
// open new WebSocket
openConnection();
// re-attach old handler to new WebSocket
webSocket.onmessage = msgHandler;
};
service.getId = function() {
return webSocket.id;
}
// Returns an already existing instance of the socket, if unavailable then creates a new one.
service.getInstance = function(name, config) {
if(!(name in instances)) {
instances[name] = createNewWebSocketInstance(config);
}
registerWebSocketHandlers(instances[name]);
return instances[name];
};
return service;
You can test WebSocket using websocket.html at websocket.org Echo Test Creating your own test
Using a text editor, copy the following code and save it as
websocket.html somewhere on your hard drive. Then simply open it in a browser. The page will automatically connect, send a message,
display the response, and close the connection.
See Linux - WebSocket test error.
I have the following code snippet which I need to extend to define multiple WebSockets and I am clueless as to how do I go about it:
var registerWebSocketHandlers = function(webSocket) {
webSocket.onclose = function(){
setTimeout(service.reopen, reconnectTimeout *= 2);
};
webSocket.onopen = function(e) {
icc.publish('webSocket.reconnect');
reconnectTimeout = defaultReconnectTimeout; //reset this
deferredSend();
};
webSocket.onerror = function(e) {
throw new Error("[WebSocket] An error occured " + e);
};
}
var openConnection = function() {
connectionWasOpenBefore = true;
webSocket = new $window.WebSocket(xyz);
webSocket.id = uniqid();
registerWebSocketHandlers(webSocket);
};
var uniqid = function() {
return (new Date().getTime()).toString(16);
}
service.setMessageEventHandler = function(cb) {
webSocket.onmessage = function(msg) {
if(msg.data.indexOf('Status: connected') === 0)
{
return;
}
var jsonObj = JSON.parse(msg.data);
cb(jsonObj);
};
};
How do I twist the code to suit the needs of multiple WebSockets and attaching the appropriate callback to it?
Use the multiton pattern.
var socketFactory = module.factory('SocketFactory', function($rootScope){
var factory = {};
var instances = {};
factory.getInstance = function(name, config){
if(!(name in instances)){
instances[name] = createNewWebSocketInstance(name, config);
}
return instances[name];
};
var createNewWebSocketInstance = function(name, config){
var webSocket = new $window.WebSocket(config.address);
webSocket.id = uniqid();
registerWebSocketHandlers(webSocket, name, config.handlers); //etc.
return webSocket;
};
var registerWebSocketHandlers = function(webSocket, name, handlers){
webSocket.onmessage = function(event){
$rootScope.$emit('SocketMessageReceived_' + name, event.data);
};
//etc...
};
return factory;
});
This will separate your different websockets by name. Use getInstance('whatever') to get a websocket labelled as 'whatever'.
var firstConfig = {url: '*****', username: '****', password: '****', etc: '****'};
// You only need to pass in the config the first time.
var firstWebSocket = SocketFactory.getInstance('firstSocket', firstConfig);
var secondConfig = {url: '####', username: '####', password: '####', etc: '####'};
var secondWebSocket = SocketFactory.getInstance('secondSocket', secondConfig);
Next, from any other area you can access the configured websockets by their instance names.
var firstWebSocket = SocketFactory.getInstance('firstSocket');
// It would probably be a good idea to add this listener in the SocketFactory instead and broadcast an event when there's a message so multiple listeners can respond to it.
firstWebSocket.onmessage = function(){...};
var secondWebSocket = SocketFactory.getInstance('secondSocket');
secondWebSocket.onmessage = function(){...};
I am writing a chrome extension using indexedDB and want to use sendMessage to pass data from the background page to the popup.
If the button is pressed, a message is sent from popup to background, and a response should be written to the 'results' div.
the logging messages are all ok, but no response is sent from within the 'openRequest.onsuccess' block.
I am not sure why the response is not received from openRequest.onsuccess yet the console message just after it is written.
output from console.log;
popup;
processMessage() - 2
background;
processMessage() - 2
processMessage() - 1
content of 'results';
processMessage() - 2
popup.js
var popupInst;
var popupPage = function() {
var mThis = this;
this.msg;
this.init = function() {
document.querySelector('#btnAdd').addEventListener('click', this.add);
};
this.add = function() {
chrome.extension.sendMessage({ add: { keyName: 'key', valueName: 'value' }}, function(response) {
mThis.msg = (response.msg)
console.log(mThis.msg);
$('#results').empty().append(mThis.msg);
});
};
}
document.addEventListener('DOMContentLoaded', function(){popupInst = new popupPage(); popupInst.init();});
background.js
var bgInst;
var backgroundPage = function()
{
var mThis = this;
this.dbName = 'test-db';
this.db;
this.init = function() {
var openRequest = window.indexedDB.open(mThis.dbName,1);
openRequest.onsuccess = function(evt) {
this.db = openRequest.result;
};
openRequest.onupgradeneeded = function(evt) {
var objStore = evt.target.result.createObjectStore(this.dbName,{keyPath:"keyName"});
objStore.createIndex("keyName","keyName",{unique:true});
objStore.createIndex("valueName","valueName",{unique:false});
};
chrome.extension.onMessage.addListener(this.processMessage);
};
this.processMessage = function(msgRequest,msgSender,msgCallback) {
if(msgRequest.add) {
var openRequest = window.indexedDB.open(mThis.dbName);
openRequest.onsuccess = function(evt) {
var str1 = 'processMessage() - 1';
msgCallback({ msg: str1 }); -> this message is never received in popup.js
console.log(str1); -> but this message is written to the log
};
var str2 = 'processMessage() - 2';
msgCallback({ msg: str2 });
console.log(str2);
}
};
}
document.addEventListener('DOMContentLoaded', function(){bgInst = new backgroundPage(); bgInst.init();});