我正在尝试在as3中发送图像,因为有些图像很大,我试图将图像分开然后发送它们,然后重新组装它们。这是代码:
发件人代码:
package
{
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.DatagramSocketDataEvent;
import flash.events.Event;
import flash.net.DatagramSocket;
import flash.net.FileReference;
import flash.utils.ByteArray;
public class test extends Sprite
{
private var socket:DatagramSocket;
private var r:FileReference;
private var loader:Loader;
public function test()
{
socket = new DatagramSocket();
socket.bind(12395, "127.0.0.1");
r = new FileReference();
r.addEventListener(Event.SELECT, loadFile);
r.browse();
}
protected function loadFile(event:Event):void
{
r.addEventListener(Event.COMPLETE, sendFile);
r.load();
}
protected function sendFile(event:Event):void
{
var b:ByteArray;
trace(r.data.bytesAvailable);
for(var i:uint = 0; i < r.data.bytesAvailable;)
{
b = new ByteArray();
if(r.data.bytesAvailable >= 1024)
{
r.data.readBytes(b, 0, 1024);
socket.send(b, 0, 0, "127.0.0.1", 12345);
trace(b.bytesAvailable);
trace(r.data.bytesAvailable);
}
else
{
r.data.readBytes(b, i, r.data.bytesAvailable);
socket.send(b, 0, 0, "127.0.0.1", 12345);
b = new ByteArray();
socket.send(b, 0, 0, "127.0.0.1", 12345);
trace(b.bytesAvailable);
trace(r.data.bytesAvailable);
break;
}
}
trace("----------------------------");
}
}
}
接收者代码:
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.DatagramSocketDataEvent;
import flash.events.Event;
import flash.net.DatagramSocket;
import flash.net.FileReference;
import flash.utils.ByteArray;
var socket:DatagramSocket;
var loader:Loader;
var b:ByteArray;
var i:uint = 0;
b = new ByteArray();
socket = new DatagramSocket();
socket.bind(12345, "127.0.0.1");
socket.addEventListener(DatagramSocketDataEvent.DATA, handleData);
socket.receive();
function handleData(event:DatagramSocketDataEvent):void
{
if(event.data.bytesAvailable != 0)
{
trace("writing bytes...");
event.data.readBytes(b, i);
trace(b.bytesAvailable);
//b.length = b.length + 1;
i = i + 1024;
}
else
{
loadImg();
}
}
function loadImg():void
{
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, addToStage);
loader.loadBytes(b);
}
function addToStage(event:Event):void
{
addChild(loader);
}
但即使发送和接收的字节完全相同,图像也不会加载。
答案 0 :(得分:0)
我只需修改发件人代码,如下所示:
else
{
r.data.readBytes(b, i, r.data.bytesAvailable);
socket.send(b, 0, 0, "127.0.0.1", 12345);
b = new ByteArray();
b.writeByte(0) // ADD THIS NEW LINE
socket.send(b, 0, 0, "127.0.0.1", 12345);
trace(b.bytesAvailable);
trace(r.data.bytesAvailable);
break;
}
它将触发loadImg函数。