send xhr-polling from other threads

This commit is contained in:
Naoyuki Kanezawa
2013-04-22 23:36:42 +09:00
parent 2c4748ab93
commit 4a7b7289d7
2 changed files with 37 additions and 23 deletions

View File

@@ -6,6 +6,8 @@ import com.github.nkzawa.emitter.Emitter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;
public class PollingXHR extends Polling {
@@ -78,6 +80,8 @@ public class PollingXHR extends Polling {
private static class Request extends Emitter {
private static final ExecutorService xhrService = Executors.newCachedThreadPool();
String method;
String uri;
String data;
@@ -106,13 +110,18 @@ public class PollingXHR extends Polling {
}
logger.info(String.format("sending xhr with url %s | data %s", this.uri, this.data));
xhrService.submit(new Runnable() {
@Override
public void run() {
BufferedWriter writer = null;
BufferedReader reader = null;
try {
if (this.data != null) {
byte[] data = this.data.getBytes("UTF-8");
if (self.data != null) {
byte[] data = self.data.getBytes("UTF-8");
xhr.setFixedLengthStreamingMode(data.length);
xhr.getOutputStream().write(data);
writer = new BufferedWriter(new OutputStreamWriter(xhr.getOutputStream()));
writer.write(self.data);
writer.flush();
}
String line;
@@ -121,15 +130,20 @@ public class PollingXHR extends Polling {
while ((line = reader.readLine()) != null) {
data.append(line);
}
this.onData(data.toString());
self.onData(data.toString());
} catch (IOException e) {
this.onError(e);
self.onError(e);
} finally {
try {
if (writer != null) writer.close();
} catch (IOException e) {}
try {
if (reader != null) reader.close();
} catch (IOException e) {}
}
}
});
}
public void onSuccess() {
this.emit("success");

View File

@@ -73,8 +73,8 @@ public class SocketTest {
public void stopServer() throws InterruptedException {
System.out.println("Stopping server ...");
serverProcess.destroy();
serverOutout.cancel(true);
serverError.cancel(true);
serverOutout.cancel(false);
serverError.cancel(false);
serverService.shutdown();
serverService.awaitTermination(3000, TimeUnit.MILLISECONDS);
}