2015-12-03 19 views
8

quindi ho avuto problemi a inviare dati binari con socket.io in node.js (client Js e client Android).Come inviare dati binari con socket.io?

Non ci sono molte informazioni né in:

http://socket.io/blog/introducing-socket-io-1-0/

http://socket.io/get-started/chat/

ho bisogno di usare presa io per inviare una matrice binaria, che creo e riempire.

l'unico codice danno è la seguente:

var socket = new WebSocket('ws://localhost'); 
socket.binaryType = 'arraybuffer'; 
socket.send(new ArrayBuffer); 

La mia risposta è muggito.

risposta

13

Infine ho lavorato con JS e Android (Java), quindi ho deciso di condividerlo con voi ragazzi.

Cominciamo con il codice del server: (Nodo js)

var http = require('http'); 

var app = http.createServer(function ejecute(request, response){}); 
var io = require('socket.io').listen(app); 


io.on('connection', function(socket) { 
     socket.on('message', function(data){ 
      console.log("recieved data:"); 
      console.log(data); 

      var bufArr = new ArrayBuffer(4); 
      var bufView = new Uint8Array(bufArr); 
      bufView[0]=6; 
      bufView[1]=7; 
      bufView[2]=8; 
      bufView[3]=9; 
      socket.emit('message',bufArr); 
     }); 
    }); 
app.listen(3000); 

Consente salto al client JavaScript

var socket = io("http://localhost:3000"); 
    socket.emit('message', 'hola from js client'); 

    socket.on('message', function(msg){ 
    var bufView = new Uint8Array(msg); 
    console.log(msg) 
    }); 

E, infine, mostriamo la (java) client Android:

final Socket socket = IO.socket("http://localhost:3000",opts); 

    socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() { 
     @Override 
     public void call(Object... args) { 
      socket.emit("message","hello from java"); 
     } 
    }); 


    socket.on("message", new Emitter.Listener() { 

     @Override 
     public void call(Object... args) { 
      byte[] bytearray = (byte[])args[0]; //received bytes 

      for (byte b : bytearray) { 
       System.out.println("byte"+b); 
      } 
     } 

    }); 

    socket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() { 
    @Override 
    public void call(Object... args) {} 
}); 

Spero che sia utile a tutti voi. Cheers!

+0

questo può aiutare https://stackoverflow.com/questions/26498114/issue-with-sending-buffer-over-socket-io#comment41630083_26498165 – DantaliaN