三、客户端
具体的布局文件就不细说了,可以看源码,这里主要列出主要实现代码。
1、网络字节转换工具类(重要)
要想实现Java和C/C++的通信,客户端得先把数据全部转换为byte数组,int、float、double类型的转换必须进行特殊处理,这里只封装了int、String的转换,其他可根据需要自行封装。
public class NetDataTransformUtils {
/**
* int 转为 ByteArray
* 将int转为低字节在前,高字节在后的byte数组
* @param n
* @return
*/
public static byte[] intToByteArray(int n) {
byte[] b = new byte[4];
b[0] = (byte) (n & 0xff);
b[1] = (byte) (n >> 8 & 0xff);
b[2] = (byte) (n >> 16 & 0xff);
b[3] = (byte) (n >> 24 & 0xff);
return b;
}
/**
* ByteArray 转为 int
* @param bArr
* @return
*/
public static int byteArrayToInt(byte[] bArr) {
int n = 0;
for(int i=0;i<bArr.length&&i<4;i++){
int left = i*8;
n+= (bArr[i] << left);
}
return n;
}
/**
* ByteArray 转为 String
* @param valArr
* @param maxLen
* @return
*/
public static String byteArrayToString(byte[] valArr,int maxLen) {
String result=null;
int index = 0;
while(index < valArr.length && index < maxLen) {
if(valArr[index] == 0) {
break;
}
index++;
}
byte[] temp = new byte[index];
System.arraycopy(valArr, 0, temp, 0, index);
try {
result= new String(temp,"GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
/**
* String 转为 ByteArray
* @param str
* @return
*/
public static byte[] stringToByteArray(String str){
byte[] temp = null;
try {
temp = str.getBytes("GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return temp;
}
}
2、首部类
public class PktHeader{
private int pktLen;
private int pktType;
public PktHeader(){
}
public PktHeader(byte[] b){
if(b.length == 4){
byte[] b1 = new byte[4];
int i;
for (i=0;i<4;i++) {
b1[i] = b[i];
}
this.pktLen = NetDataTransformUtils.byteArrayToInt(b1);
}else if(b.length >= 8){
byte[] b1 = new byte[4];
byte[] b2 = new byte[4];
int i;
for (i=0;i<4;i++) {
b1[i] = b[i];
}
this.pktLen = NetDataTransformUtils.byteArrayToInt(b1);
for (i=0;i<4;i++) {
b2[i] = b[4+i];
}
this.pktType = NetDataTransformUtils.byteArrayToInt(b2);
}
}
public PktHeader(int pktLen, int pktType){
this.pktLen = pktLen;
this.pktType = pktType;
}
public int getPktLen() {
return pktLen;
}
public void setPktLen(int pktLen) {
this.pktLen = pktLen;
}
public int getPktType() {
return pktType;
}
public void setPktType(int pktType) {
this.pktType = pktType;
}
}
3、数据类(列举两个典型: 发送数据类、响应数据类)
(1)发送数据类
每次向服务器发送这个类对象前,先转换为byte数组,再发送。
public class LoginPkt{
private PktHeader header;
private String username;
private String password;
public LoginPk

本文介绍了如何使用Socket编程在Android客户端实现远程控制PC上的音乐播放器。主要内容包括网络字节转换工具类的实现,数据类的设计(如发送和响应数据类),以及Socket操作线程的细节,如发送和接收数据的策略。此外,还提到了登录、获取音乐列表以及播放、停止音乐的操作,并通过Map记录歌曲播放状态来避免重复播放。
最低0.47元/天 解锁文章
2567

被折叠的 条评论
为什么被折叠?



