【发布时间】:2011-08-03 17:29:24
【问题描述】:
我正在为 Android 开发一个 Web 服务器,尽管我花了几天时间试图修复它,但我对这个特定的错误束手无策。我正在尝试从浏览器读取请求,并且代码大部分时间都可以正常工作,但是有 5% 的请求失败并且它会抛出随机 SocketTimeoutExceptions,甚至没有从 Socket 读取单个字符。
我已经用不同的浏览器对此进行了测试,并且所有浏览器都会发生这种情况,所以问题很可能出在我身上。以下是相关代码,尽可能精简:
public class ServerThread extends Thread {
private ServerSocket ss = null;
private boolean isRunning;
private ExecutorService threadPool = new ThreadPoolExecutor(2, 12,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
public ServerThread() {
}
public synchronized void run() {
ss = new ServerSocket(8080, 1);
isRunning = true;
while (isRunning) {
Socket clientSocket = null;
try {
if (ss != null) {
clientSocket = ss.accept();
if (isRunning) {
this.threadPool.execute(new HTTPSession(clientSocket));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
还有:
public class HTTPSession implements Runnable {
private Socket mSocket = null;
public HTTPSession (Socket s) {
mSocket = s;
}
public void run() {
InputStream ips = null;
try {
mSocket.setSoTimeout(15000);
ips = mSocket.getInputStream();
ips.read();
}
catch (Exception e) {
e.printStackTrace();
Log.v("HTTPSession", "Socket connected: " + mSocket.isConnected() + ", Socket closed: " + mSocket.isClosed() + ", InputShutdown: " + mSocket.isInputShutdown());
}
finally {
try { ips.close(); } catch (IOException ioe) { }
try { mSocket.close(); } catch (IOException ioe) { }
}
}
}
所以 ServerThread 接受连接,HTTPSession 尝试从 Socket 读取,有时它会在 15 秒后抛出 SocketTimeoutException。
在这种情况下,catch 中的 Log 语句的输出是: 套接字已连接:true,套接字已关闭:false,InputShutDown:false
什么给了?当然 15 秒的等待时间就足够了,主流网络浏览器似乎不太可能不发送任何数据,那我为什么看不到呢?
我将不胜感激有关此问题的任何意见。
【问题讨论】:
标签: java android multithreading sockets