第一次发送消息,为什么我不能再次发送消息(Android Socket编程)
Message was send for first time, Why I can't send message again (Android Socket Programming)
我为客户端创建了套接字编程class。已建立连接。服务器向客户端发送消息。客户端可以从服务器获取消息。但客户只发送一个答案。为什么?输出流是不是错了?
public class Message extends AsyncTask<byte[], Void, Void> {
Socket s;
public static byte[] recv;
@Override
protected Void doInBackground(byte[]... voids) {
byte[] message = voids[0];
try {
s = new Socket(destIp, destPort);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeInt(message.length);
dos.write(message);
dos.flush();
InputStream inFromServer = s.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
byte[] buffer = new byte[200];
int read = 0;
while ((read = in.read(buffer, 0, buffer.length)) != -1) {
// in.read(buffer);
recv = Arrays.copyOf(buffer, read);
Context context = getContext();
Intent intentManager = new Intent(context, ManagerService.class);
context.startService(intentManager);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
我在启动 asynctask 的部分修复了这个问题
new MessageReceive().execute(sendData);
至
new MessageReceive().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,sendData);
我为客户端创建了套接字编程class。已建立连接。服务器向客户端发送消息。客户端可以从服务器获取消息。但客户只发送一个答案。为什么?输出流是不是错了?
public class Message extends AsyncTask<byte[], Void, Void> {
Socket s;
public static byte[] recv;
@Override
protected Void doInBackground(byte[]... voids) {
byte[] message = voids[0];
try {
s = new Socket(destIp, destPort);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeInt(message.length);
dos.write(message);
dos.flush();
InputStream inFromServer = s.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
byte[] buffer = new byte[200];
int read = 0;
while ((read = in.read(buffer, 0, buffer.length)) != -1) {
// in.read(buffer);
recv = Arrays.copyOf(buffer, read);
Context context = getContext();
Intent intentManager = new Intent(context, ManagerService.class);
context.startService(intentManager);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
我在启动 asynctask 的部分修复了这个问题
new MessageReceive().execute(sendData);
至
new MessageReceive().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,sendData);