所以我在node.js(Js客户端和Android客户端)中使用socket.io发送二进制数据时遇到了麻烦.
在以下情况中没有太多信息:
http://socket.io/blog/introducing-socket-io-1-0/
http://socket.io/get-started/chat/
我需要使用socket io发送一个二进制数组,我创建并填充.
他们提供的唯一代码如下:
var socket = new WebSocket('ws://localhost'); socket.binaryType = 'arraybuffer'; socket.send(new ArrayBuffer);
我的回答是吼叫.
最后我使用JS和Android(Java),所以我决定与你们分享.
让我们从服务器代码开始:(节点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);
让我们跳转到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) });
最后,让我们展示Android(java)客户端:
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) {} });
我希望它对大家都有用.干杯!