当客户端连接到服务器时,他们应该能够将图像发送到服务器,因此服务器可以显示接收的图像。我在服务器端使用了AsyncTask来完成任务。
当一个客户端连接到服务器时,一切似乎都很好,图像从该客户端接收,但是当下一个客户端连接它不工作时,有时第一个客户端断开连接或图像没有从一个客户端接收或两者都接收。
有人可以帮我弄这个吗?我做错了吗?
服务器端AsyncTask
public static class FileServerAsyncTask extends AsyncTask {
private Context context;
private TextView statusText;
public FileServerAsyncTask(Context context, View statusText) {
this.context = context;
this.statusText = (TextView) statusText;
}
@Override
protected String doInBackground(Void... params) {
class ClientWorker implements Runnable {
private Socket client;
private final File f;
//Constructor
ClientWorker(Socket client, File f) {
this.client = client;
this.f = f;
}
public void run(){
try{
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
}
try {
ServerSocket serverSocket = new ServerSocket(8988);
Log.d(WiFiDirectActivity.TAG, "Server: Socket opened");
boolean check = true;
while(check){
ClientWorker w;
try{
//server.accept returns a client connection
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
w = new ClientWorker(serverSocket.accept(),f);
Thread t = new Thread(w);
t.start();
return f.getAbsolutePath();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
serverSocket.close();
return null;
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
@Override
protected void onPostExecute(String result) {
if (result != null) {
statusText.setText("File copied - " + result);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
@Override
protected void onPreExecute() {
statusText.setText("Opening a server socket");
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
} catch (IOException e) {
Log.d(WiFiDirectActivity.TAG, e.toString());
return false;
}
return true;
}
答案 0 :(得分:1)
我认为你所需要的只是改变这些方面:
w = new ClientWorker(serverSocket.accept(),f);
Thread t = new Thread(w);
t.start();
return f.getAbsolutePath();
你的问题是在第一个客户端连接后你走出doInbackground。你必须使用onProgressPublish()来发送中间结果并保持循环并且不要关闭服务器。
所以在连接到第一个客户端并将其发送到您创建的套接字后,您将通过返回f.getAbsolutePath()离开主循环;并从服务器出去。所有代码都是正确的,除了发送中间结果使用函数(onProgressPublish())。