/**
* 设置监听
*
* @param socketCallback
*/
public void setSocketCallback(TcpSocketCallback socketCallback) {
this.mTcpSocketCallback = socketCallback;
}
public SocketClient() {
}
final Object LOCK = new Object();
public void startTcpSocket(final String ip, int port) {
ThreadPool.getInstance().execute(new Runnable() {
@Override
public void run() {
// 确保一个连接操作。
synchronized (LOCK) {
if (isConnection())
return;
if (startTcpConnection(ip, port)) {// 尝试建立 TCP 连接
startReceiveTcpThread();
LogWrapper.d(TAG, "连接成功");
if (mTcpSocketCallback != null)
mTcpSocketCallback.onConnect(ip, port);
} else {
LogWrapper.d(TAG, "连接失败, 开始断开...");
disConnect();
}
}
}
});
}
private final Object LOCKS = new Object();
/**
* 创建接收线程
*/
private void startReceiveTcpThread() {
ThreadPool.getInstance().execute(new Runnable() {
@Override
public void run() {
try {
while (true) {
synchronized (LOCKS) {
byte[] srcType = new byte[4];
is.read(srcType);
int type = BytesUtils.bytes2Int(srcType);
byte[] src = new byte[4];
is.read(src);
int len = BytesUtils.bytes