我有Java Socket发送.TXT文件(10 MB)。但AS3仅获得63 Kb。我不明白字节的丢失......
(服务器)Java Source Socket。将文件发送到客户端AS3
public void sendFile(String fileName) {
File myFile = new File(fileName);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
OutputStream os = clientSocket.getOutputStream();
byte[] fileSize = intToByte(mybytearray.length);
byte[] clientData = new byte[(int) myFile.length() + mybytearray.length];
System.arraycopy(fileSize, 0, clientData, 0, fileSize.length);
System.arraycopy(mybytearray, 0, clientData, 4, mybytearray.length);
DataOutputStream dos = new DataOutputStream(os);
dos.write(clientData, 0, clientData.length);
dos.flush(); }
来自Java的客户端/接收字节AS3
private function onResponse(e:ProgressEvent):void {
var file:File;
var fs:FileStream;
var fileData:ByteArray = new ByteArray();
file = File.documentsDirectory.resolvePath("tmpReceive.txt");
fs = new FileStream();
fs.addEventListener(Event.CLOSE,onCloseFileReceive);
if(_socket.bytesAvailable > 0) {
while(_socket.bytesAvailable) {
_socket.readBytes(fileData,0,0);
} }
fs.open(file, FileMode.WRITE);
fs.writeBytes(fileData);
fs.close(); }
答案 0 :(得分:0)
它说"套接字以异步方式接收数据" in the flash.net.Socket
manual,这意味着您必须侦听该套接字上的事件,并且当有事件时,您从套接字读取字节,并且一旦收到"关闭"事件或通过任何其他方式发现文件的结尾,只有这样您才能将文件刷新到磁盘。我看到你首先发送一个包含文件大小的4字节整数值,所以使用这个值来确定文件是否通过套接字完全读取。
var fileSize:int=0;
var fileData:ByteArray=new ByteArray();
_socket.addEventListener(flash.events.ProgressEvent.SOCKET_DATA,readFromSocket);
function readFromSocket(e:ProgressEvent):void {
if (_socket.bytesAvailable==0) return; // no data
if (fileSize==0) {
fileSize=_socket.readInt();
// get file size if we've just initialized file transfer
fileData.length=0;
fileData.position=0; // clear the array to not mess with previous file, if any
} else if (fileSize==fileData.length) return; // still flushing file to disk
if (_socket.bytesAvailable>0) {
_socket.readBytes(fileData,0,Math.min(fileSize-fileData.length,_socket.bytesAvailable));
// get all available bytes up to received file's length
// there might not be enough, so we use minimum of what's unread and what's present
if (fileData.length>=fileSize) {
trace("File received: size given",fileSize","size received", fileData.length);
// these should be equal, if not, you have more to dig
// now dump the file, you have the code, insert it here
// and don't forget to set fileSize to 0 once you have received
// the "end of writing file to disk" event, so that you can
// receive another file via same socket
// once you'll perfect this, consider sending an UTF-string
// with file name prior to sending file.
}
}
}
你的63kb值似乎比套接字服务的字节少了64kb,这会为应用程序生成一个ProgressEvent.SOCKET_DATA
的事件,而你假设所有10MB的数据都被一次性放入套接字。 / p>