【发布时间】:2016-11-21 09:32:46
【问题描述】:
我在向服务器发送数据时遇到问题,我使用套接字连接服务器。要将数据发送到服务器,我使用 AsyncTask。我有一个问题:
当应用程序发送数据时,我的应用程序看不到完成此操作,它从不使用onPostExecute()。
这是我的代码:
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port) {
dstAddress = addr;
dstPort = port;
}
@Override
protected Void doInBackground(Void... arg0) {
// if (pingHost(1000)) {
socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
byte[] theByteArray = message.getBytes();
lengthMessage = (short) theByteArray.length;
outputStream.writeByte((byte) 0xB);
outputStream.writeByte((byte) 0xA);
outputStream.writeByte((byte) 0xA);
outputStream.writeByte((byte) 0xD);
outputStream.writeShort(lengthMessage);
outputStream.write(theByteArray);
outputStream.writeShort(width);
outputStream.writeShort(height);
outputStream.writeInt(lengthbmp);
outputStream.writeInt(lengthResizebmp);
outputStream.writeShort(11);
outputStream.write(imageInByte );
outputStream.write(imageResizeInByte);
outputStream.writeByte((byte) 0xB);
outputStream.writeByte((byte) 0xE);
outputStream.writeByte((byte) 0xE);
outputStream.writeByte((byte) 0xF);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int bytesRead;
InputStream inputStream = socket.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
outputStream.flush();
outputStream.close();
} catch (UnknownHostException e) {
e.printStackTrace();
isSuccsess = false;
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
e.printStackTrace();
Log.d("la", "nie udało sie");
isSuccsess = false;
response = "IOException: " + e.toString();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (socket != null) {
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(isSuccsess){
Toast.makeText(MainActivity.this, "Zdjęcie zostało wysłane !" , Toast.LENGTH_LONG).show();
bm = null;
clearEt();
ivImage.setImageBitmap(bm);
}
else{
Toast.makeText(MainActivity.this , "Nie udało się wysłać zdjęcia !" , Toast.LENGTH_LONG).show();
}
pbWheel.setVisibility(View.INVISIBLE);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pbWheel.setVisibility(View.VISIBLE);
}
}
【问题讨论】:
-
请不要再次发布您的问题。更好地回答您第一篇帖子中的问题stackoverflow.com/questions/40679274/…
-
你检查过控制台吗?我的意思是,有什么例外吗?
-
@mallaudin 也不例外
标签: java android sockets android-asynctask