您的位置:首页 > 编程语言 > Java开发

Java传递音频给PC端C#程序<二>

2017-04-18 11:45 387 查看
采用报头形式发送文件,发送的整块字节由4部分组成。

1. 文件的名称转成字节后,计算该字节长度;

2. 文件名转成的字节 ;

3. 把文件转成字节,计算该文件字节的长度;

4. 文件转的字节

服务端通过读取长度知道后面该长度的字节为文件名或文件。

文件名长度用4个字节装载文件名长度不限文件长度用4个字节装载文件长度不限
A1A2A3A4
01110111…111000000…01110111…0101010100100001110101001001010010101010…
在字节流中,A1占体积4个字节,A1表示A2的长度,A3占体积4个字节,A3表示A4的长度

- 第一步,建立连接

private ExecutorService executor  = Executors.newFixedThreadPool(5);
.
.
.

Socket socket = new Socket(host, Integer.parseInt(port));
executor.submit(new SendMusicRunnable(socket, musicEntity));


第二步,建立实现Runnable接口的类

private class SendMusicRunnable implements Runnable {
private Socket socket;
private MusicEntity musicEntity;

SendMusicRunnable(Socket socket, MusicEntity musicEntity) {
this.socket = socket;
this.musicEntity = musicEntity;
}

@Override
public void run() {
String url = musicEntity.getUrl();//文件在手机里的位置
String fileName= musicEntity.getFileName();//需要传递后缀,不能使用getTitle

//准备标题和标题字节长度
//标题内容
byte[] titleContentBytes = fileName.getBytes(Charset.defaultCharset());
int titleLength = titleContentBytes.length;
//标题转字节后的长度,用4字节装标题内容转字节后的长度
byte[] titleLengthBytes = intToByteArray(titleLength);
//准备文件长度
File file = new File(url);
long musicLength = file.length();//文件属性数组
//文件长度转字节后的长度,4字节装文件大小转字节后的长度
byte[] fileLengthBytes = intToByteArray((int) musicLength);
try {
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

DataOutputStream dos = new DataOutputStream(bos);
DataInputStream dis = new DataInputStream(bis);

//写属性
dos.write(titleLengthBytes);//1.写入标题的字节长度
dos.write(titleContentBytes);//2.写入标题
dos.write(fileLengthBytes);//3.写入文件的字节长度
dos.flush();

int end = -1;
byte[] bytes = new byte[1024 * 1024];
int length = bytes.length;
long currentSize = 0;

//4.写入文件
while ((end = dis.read(bytes, 0, length)) != -1) {
dos.write(bytes, 0, end);
}
dos.flush();
//5.传递结束
Log.e("tag", "【SendMusicRunnable】类的方法:【run】: " + "传文件结束");
} catch (IOException e) {
//传输失败
e.printStackTrace();
}finally{
if(dis!=null){
dis.close();
}
if(dos!=null){
dos.close();
}
}
}
}

/**
* int类型转成4个字节的byte[]
**/
private static byte[] intToByteArray(int i) {
byte[] result = new byte[4];
result[0] = (byte) ((i >> 24) & 0xFF);
result[1] = (byte) ((i >> 16) & 0xFF);
result[2] = (byte) ((i >> 8) & 0xFF);
result[3] = (byte) (i & 0xFF);
return result;
}


至此客户端传输结束。

C#写的服务端执行流程大概如下

1. 开始接收字节流;

2. 判断接收了4个字节,然后知道接下来的n个字节是文件名称;

3. 读取文件名称结束后,即读到第4+n字节,再截获第(4+n)~(4+n+4)字节;

4. 知道文件长度为xn;

5. 然后一直读到结束,保存文件到指定地址,判断文件长度和xn是否相等,不相等删除文件。

下次再更新C#写服务端的代码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java c# android 文件传输