2016-09-18 24 views
1

我試圖通過React-Native中的Websocket連接來連接到Watson TTS API。連接已建立,我可以向服務器發送消息,但是我以某種方式從服務器返回的數據總是空的。React-Native Websocket事件數據屬性丟失

好像event.data屬性完全缺失。如果我在react-native中將它登錄到控制檯,我會得到'undefined'。如果我在瀏覽器中使用相同的代碼,一切正常。

我使用的反應原生0.33,這裏是我的代碼:

function connectTTS(token) { 
    var voice = "de-DE_BirgitVoice"; 
    var format = 'audio/basic'; 
    var token = token; 
    var wsURI = "wss://stream.watsonplatform.net/text-to-speech/api/v1/synthesize?voice=" + voice + "&watson-token=" + token; 

    function onOpen(evt) { 
    var message = { 
     text: "Hello world.", 
     accept: format 
    }; 
    // note: the Text to Speech service currently only accepts a single message per WebSocket connection 
    websocket.send(JSON.stringify(message)); 
    } 

    var audioParts = []; 
    var finalAudio; 
    function onMessage(evt) { 
    console.log(evt.data); 
    if (typeof evt.data === 'string') { 
     console.log('Received string message: ', evt.data) 
    } else { 
     console.log('Received ' + evt.data.size + ' binary bytes', evt.data.type); 
     audioParts.push(evt.data); 
    } 
    } 

    function onClose(evt) { 
    console.log('WebSocket closed', evt.code, evt.reason); 
    console.log(audioParts); 
    console.log(format); 
    finalAudio = new Blob(audioParts, {type: format}); 
    console.log('final audio: ', finalAudio); 
    } 

    function onError(evt) { 
    console.log('WebSocket error', evt); 
    } 

    var websocket = new WebSocket(wsURI); 
    websocket.onopen = onOpen; 
    websocket.onclose = onClose; 
    websocket.onmessage = onMessage; 
    websocket.onerror = onError; 

} 

這將是巨大的,如果有人有更多的反應本地/ WebSocket的經驗能幫助我找到解決方案。謝謝。

回答

0

在react-native達到0.53(當前的最新版本)時,反應原生WebSocket事件處理依賴於事件目標墊片1.1.1庫,它包裝一個事件並且不包含數據到包裝事件,因此爲了獲得WebSocket事件數據,您可以使用以下兩種方法之一:

  1. __proto__獲取數據;
  2. 重寫event-target-shim 1.1.1;

第一種方法:

  • 使用<your event>.__proto__.__proto__.data

第二種方法:

  • 叉事件目標墊片和復位到事件目標墊片1.1。 1;
  • fork react-native;
  • 將以下代碼添加到event-target-shim/lib/event-wrapper.js;
  • 重寫react-native package.json以使用event-target-shim的分叉版本;
  • 重寫你項目的package.json;

代碼在exports.createEventWrapper添加var propertyDefinition = {...}後:

if (event.type === "message"){ 
    propertyDefinition.data = {value: event.data, enumerable: true}; 
}