package com.basic.security.utils.socket;
|
|
import android.os.SystemClock;
|
|
import com.basic.security.base.BaseApplication;
|
import com.basic.security.manager.OfficeDeviceManager;
|
import com.basic.security.model.OfficeDevice;
|
import com.basic.security.utils.Constants;
|
import com.basic.security.utils.SocketUtil;
|
|
import java.net.ServerSocket;
|
import java.net.Socket;
|
import java.util.Map;
|
|
public class OfficeSocketServer {
|
|
public static boolean serverStarted = false;
|
|
public static void startSocketServer() {
|
if (serverStarted) {
|
return;
|
}
|
BaseApplication.getApplication().executorService.execute(() -> {
|
ServerSocket server = null;
|
try {
|
server = new ServerSocket(Constants.officeServerPort);
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
while (true) {
|
try {
|
if (server == null) {
|
break;
|
}
|
serverStarted = true;
|
Socket client = server.accept();
|
OfficeAcceptedClient officeAcceptedClient = new OfficeAcceptedClient(client);
|
officeAcceptedClient.start();
|
} catch (Exception e) {
|
e.printStackTrace();
|
} finally {
|
SystemClock.sleep(3000);
|
}
|
}
|
});
|
|
}
|
|
public static class OfficeAcceptedClient extends Thread {
|
|
Socket mSocket;
|
|
public OfficeAcceptedClient(Socket client) {
|
mSocket = client;
|
}
|
|
@Override
|
public void run() {
|
SocketUtil socketUtil = new SocketUtil();
|
try {
|
socketUtil.setSocket(mSocket);
|
Map<String, String> map = socketUtil.readJsonAsMap();
|
String ip = map.get("ip");
|
String deviceName = map.get("deviceName");
|
if (deviceName == null || "null".equals(deviceName)) {
|
deviceName = "";
|
}
|
if (ip != null && ip.length() > 0) {
|
Map<String, String> officeDevice = map;
|
officeDevice.put("ip", ip);
|
officeDevice.put(OfficeDevice.deviceIp, ip);
|
officeDevice.put(OfficeDevice.deviceName, deviceName);
|
OfficeDeviceManager.addOfficeDevice(officeDevice);
|
socketUtil.writeMessage("result", "ok");
|
} else {
|
socketUtil.writeMessage("result", "error");
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
} finally {
|
socketUtil.close();
|
}
|
}
|
|
}
|
|
}
|