序号 | 代码功能 |
|---|---|
1 | 建立LocalSocket客户端连接并接收消息。 |
2 | 通过Socket发送消息与Socket Server进行通信。 |
3 | 断开与Socket Server的连接。 |
4 | WLAN连接不可上网热点,App绑定LTE网络不生效解决方案示例代码。 |
通过如下方式,应用可以与名为resmon的Server建立Socket连接,启动接收线程监听Socket,接收Server的返回消息。客户端接收到的消息由消息头和消息体组成,参见消息格式。应用可以根据响应消息头和请求消息头的长度,偏移相应的位置得到符合文档中定义的JSON字符串消息体。
/**
* 1.create socket, socketName is "resmon"
* 2.connect server
* 3.new Thread to receive msg from server
* 4.received msg from server, include msg head and body
* 5.get msgType(MSGTYPE_BEGIN_INDEX = 6, MSGTYPE_END_INDEX = 7), revMsg[MSGTYPE_BEGIN_INDEX] == 1 is reqMsg, revMsg[MSGTYPE_BEGIN_INDEX] == 2 is respMsg
* 6.get body msg. bodyBegin is REQ_HEAD_LEN=46 or RESP_HEAD_LEN=44
* 7.get json string, like this:{"apiId":2000, "retCode":0, "netInfo":[{"netInterface":wlan00, "label":0}, {"netInterface":rmnet00, "label":1}]}
* 8.do something by yourself
*/
private Boolean openLocalSocket(){
try{
Log.d(TAG, "---------> Enter OpenSocket");
// 1.create socket, socketName is resmon
clientSocket = new LocalSocket();
clientSocketAddr = new LocalSocketAddress(socketName, LocalSocketAddress.Namespace.ABSTRACT);
// 2.connect server
clientSocket.connect(clientSocketAddr);
// 3.new Thread to receive msg from server
final BufferedReader readStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
new Thread(new Runnable() {
@Override
public void run() {
try{
String respMsg = "";
int readed = 0;
while (readed != -1) {
char[] revMsg = new char[BUFFER_SIZE];
char[] revTmpMsg = new char[BUFFER_SIZE];
// 4.received msg from server, include msg head and body
readed = readStream.read(revMsg, 0, BUFFER_SIZE);
// 5.get msgType(MSGTYPE_BEGIN_INDEX = 6,
// MSGTYPE_END_INDEX = 7),revMsg[MSGTYPE_BEGIN_INDEX] == 1
// is reqMsg, revMsg[MSGTYPE_BEGIN_INDEX] == 2 is respMsg
msgType[0] = revMsg[MSGTYPE_BEGIN_INDEX];
msgType[1] = revMsg[MSGTYPE_END_INDEX];
int bodyBegin = RESP_HEAD_LEN;
if (msgType[0] == 1) {
bodyBegin = REQ_HEAD_LEN;
}
// 6.get body msg. bodyBegin is REQ_HEAD_LEN=46 or RESP_HEAD_LEN=44
for(int i = 0; i < revMsg.length - bodyBegin; i++){
revTmpMsg[i] = revMsg[bodyBegin + i];
}
// 7.get json string
respMsg = String.valueOf(revTmpMsg);
}
}catch(IOException e){
Log.d(TAG, e.getMessage());
}
}
}).start();
}catch (IOException e){
Log.d(TAG, e.getMessage());
return false;
}
return true;
} 消息包含消息头和消息体,消息头按照文档描述的结构填充,消息体符合如下的JSON结构,通过第一步创建的的Socket将头和尾拼接起来可发送给Socket Server。如下例子是发送注册消息的例子,发送获取网络接口,接口网络信号以及绑定接口消息同理按照如下方式实现。
/**
* 1.generate msg head,hdrData is byte[]
* 2.generate msg head and body, body is as this:{"apiId":1000}"or {"apiId":2001, "netInterface":"wlan00"}
* 3.send out by socket
* @return success or fail
*/
private Boolean regApp(){
try{
if (clientSocket == null) {
return false;
}
// 1.generate msg head byte
hdrData = msgHeader.getNewHeaderMsg(regMsg.length());
// 2.generate msg body byte
byte[] msgByte = regMsg.getBytes();
// 3.merge hdrData and msg body byte
byte[] headMsgByte = mergeByte(hdrData, msgByte);
// 4.send out byte by socket
clientSocket.getOutputStream().write(headMsgByte);
} catch (IOException e) {
Log.d(TAG, e.getMessage());
return false;
}
return true;
}
/**
* merge two byte array
*
* @param byte1 byte array to be merged
* @param byte2 byte array to be merged
* @return merged byte array
*/
private byte[] mergeByte(byte[] byte1, byte[] byte2) {
byte[] byte3 = new byte[byte1.length + byte2.length];
System.arraycopy(byte1, 0, byte3, 0, byte1.length);
System.arraycopy(byte2, 0, byte3, byte1.length, byte2.length);
return byte3;
} 其中,消息头的生成方式如下:
public MsgHeader(){
this.hdrBegin = new byte[]{0x50, 0x43, 0x44, 0x48};
this.version = new byte[]{0x10, 0x00};
this.msgType = new byte[]{0x01, 0x00};
this.funcId = new byte[]{0x01, 0x00};
this.bodyLen = new byte[]{0x00, 0x00, 0x00, 0x00};
this.reqId = new byte[]{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00};
this.timeStamp = new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,0x00};
this.bodyFmt = new byte[] {0x03, 0x00, 0x00, 0x00};
this.reserve1 = new byte[] {0x00, 0x00, 0x00, 0x00};
this.reserve2 = new byte[] {0x00, 0x00, 0x00, 0x00};
this.reserve3 = new byte[] {0x00, 0x00, 0x00, 0x00};
} public byte[] getNewHeaderMsg(int bodyLen){
updateBodyLen(bodyLen);
updateReqId();
return byteMergerAll(this.hdrBegin, this.version, this.msgType, this.funcId, this.bodyLen, this.reqId, this.timeStamp, this.bodyFmt, this.reserve1, this.reserve2, this.reserve3);
} 调用第一步创建的Socket的close方法即可关闭与服务器的连接。
/**
* close socket
*
* @return success or fail
*/
private Boolean closeLocalSocket() {
try {
if (clientSocket == null) {
return false;
}
// close socket
clientSocket.close();
showTip("close socket success");
} catch (IOException e) {
Log.d(TAG, e.getMessage());
return false;
}
return true;
} private void startMobileDataNetwork() {
if (mMobileNetRequestCallback != null || mCM == null) {
return;
}
NetworkRequest mobileNetworkRequest =
new NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build();
mMobileNetRequestCallback = new ConnectivityManager.NetworkCallback();
mCM.requestNetwork(mobileNetworkRequest, mMobileNetRequestCallback);
} private class NetworkStateCallback extends ConnectivityManager.NetworkCallback {
@Override
public void onAvailable(Network network) {
if (network == null || mCM == null) {
return;
}
Network activeNet = mCM.getActiveNetwork(); // for my uid
if (network.equals(activeNet)) {
mDefaultNet = network;
}
NetworkCapabilities netCap = mCM.getNetworkCapabilities(network);
if (netCap == null || netCap.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
return;
}
if (netCap.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
if (mWifiNet == null) {
// WiFi changes to connected
}
mWifiNet = network;
} else if (netCap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
if (mMobileNet == null) {
// mobile changes to connected
}
mMobileNet = network;
} else {
// do nothing
}
}
@Override
public void onLost(Network network) {
if (network == null || mCM == null) {
return;
}
if (mDefaultNet != null && mDefaultNet.equals(network)) {
mDefaultNet = null;
}
NetworkCapabilities netCap = mCM.getNetworkCapabilities(network);
if (netCap != null && netCap.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
return;
}
if ((netCap != null && netCap.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))
|| (netCap == null && network.equals(mWifiNet))) {
if (mWifiNet != null) {
// WiFi changes to disconnected
}
mWifiNet = null;
} else if ((netCap != null && netCap.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR))
|| (netCap == null && network.equals(mMobileNet))) {
if (mMobileNet != null) {
// mobile changes to disconnected
}
mMobileNet = null;
} else {
// do nothing
}
}
} private InetAddress[] queryDnsOnMobile(String host) {
if (mMobileNet == null) {
return null;
}
InetAddress[] address = null;
try {
address = mMobileNet.getAllByName(host);
} catch (Exception e) {
Log.d(TAG, "queryDns on mobile failed: " + e);
}
return address;
} private void bindSocketOnMobile(FileDescriptor fd) { // input para can also be 'Socket socket'
if (mMobileNet == null) {
return;
}
try {
mMobileNet.bindSocket(fd);
} catch Exception e) {
// do something
}
}