主要问题出现在客户端接收服务端数据,会出现:接收不到第一条数据,但是继续发第二条数据能够接收到,第三条又收不到,第四条又可以。接收我写了一个循环代码接收服务端传上来的数据:
Runnable runnable = new Runnable() {
@Override
public void run() {
while (socket.isConnected() == true) {
byte[] buf = new byte[8];
int len = 0;
try {
inputStream = socket.getInputStream();
inputStream.read(buf);
len = inputStream.read(buf);
} catch (IOException e) {
e.printStackTrace();
}
//注意charset.forName 字符编码,utf-8中文。。。。。
try {
receData = new String(buf, 0, len, Charset.forName("utf-8"));
} catch (Exception e) {
e.printStackTrace();
}
//通过广播将数据传给Activity
Intent intent = new Intent();
intent.putExtra("receData", bytesToHexString(buf));
intent.setAction("service.data");
sendBroadcast(intent);
}
}
};
ThreadPoolmanager.getInstance().executor(runnable);
}
整体的发送数据和接收数据代码如下:
public class SocketService extends Service {
/*socket*/
public Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
/*连接线程*/
private Thread connectThread;
private Timer timer = new Timer();
private final SocketBinder sockerBinder = new SocketBinder();
private String ip;
private String port;
private TimerTask task;
private String receData;
/*默认重连*/
private boolean isReConnect = true;
private final Handler handler = new Handler(Looper.getMainLooper());
private String mReceData;
private Handler mHandler;
@Override
public IBinder onBind(Intent intent) {
return sockerBinder;
}
public class SocketBinder extends Binder {
/*返回SocketService 在需要的地方可以通过ServiceConnection获取到SocketService */
public SocketService getService() {
return SocketService.this;
}
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
/*拿到传递过来的ip和端口号*/
ip = intent.getStringExtra(Constants.INTENT_IP);
port = intent.getStringExtra(Constants.INTENT_PORT);
/*初始化socket*/
initSocket();
return super.onStartCommand(intent, flags, startId);
}
/*初始化socket 接收数据*/
private void initSocket() {
if (socket == null && connectThread == null) {
connectThread = new Thread(new Runnable() {
@Override
public void run() {
socket = new Socket();
try {
/*超时时间为2秒*/
socket.connect(new InetSocketAddress(ip, Integer.parseInt(port)), 2000);
/*连接成功的话 发送心跳包*/
if (socket.isConnected()) {
/*因为Toast是要运行在主线程的 这里是子线程 所以需要到主线程哪里去显示toast*/
toastMsg("socket已连接");
/*发送连接成功的消息*/
EventMsg msg = new EventMsg();
msg.setTag(Constants.CONNET_SUCCESS);
EventBus.getDefault().post(msg);
/*发送心跳数据*/
// sendBeatData();
Runnable runnable = new Runnable() {
@Override
public void run() {
while (socket.isConnected() == true) {
byte[] buf = new byte[8];
int len = 0;
try {
inputStream = socket.getInputStream();
inputStream.read(buf);
len = inputStream.read(buf);
} catch (IOException e) {
e.printStackTrace();
}
//注意charset.forName 字符编码,utf-8中文。。。。。
try {
receData = new String(buf, 0, len, Charset.forName("utf-8"));
} catch (Exception e) {
e.printStackTrace();
}
//通过广播将数据传给Activity
Intent intent = new Intent();
intent.putExtra("receData", bytesToHexString(buf));
intent.setAction("service.data");
sendBroadcast(intent);
}
}
};
ThreadPoolmanager.getInstance().executor(runnable);
}
} catch (IOException e) {
e.printStackTrace();
if (e instanceof SocketTimeoutException) {
toastMsg("连接超时,正在重连");
releaseSocket();
} else if (e instanceof NoRouteToHostException) {
toastMsg("该地址不存在,请检查");
stopSelf();
} else if (e instanceof ConnectException) {
toastMsg("连接异常或被拒绝,请检查");
stopSelf();
}
}
}
});
/*启动连接线程*/
connectThread.start();
}
}
/*因为Toast是要运行在主线程的 所以需要到主线程哪里去显示toast*/
private void toastMsg(final String msg) {
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
});
}
/*发送数据*/
public void sendOrder(final byte[] order) {
if (socket != null && socket.isConnected()) {
/*发送指令*/
new Thread(new Runnable() {
@Override
public void run() {
try {
outputStream = socket.getOutputStream();
if (outputStream != null) {
outputStream.write(order);
outputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} else {
toastMsg("socket连接错误,请重试");
}
}
/*释放资源*/
private void releaseSocket() {
if (task != null) {
task.cancel();
task = null;
}
if (timer != null) {
timer.purge();
timer.cancel();
timer = null;
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
outputStream = null;
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
socket = null;
}
if (connectThread != null) {
connectThread = null;
}
/*重新初始化socket*/
if (isReConnect) {
initSocket();
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("SocketService", "onDestroy");
isReConnect = false;
releaseSocket();
}
}
问题出在这:
你这给的只是客户端的吗?服务端的代码呢?