【发布时间】:2009-09-10 20:24:36
【问题描述】:
我的应用中有一个自制的网络服务器。此 Web 服务器为进入套接字的每个请求生成一个新线程以被接受。我希望网络服务器等到它刚刚创建的线程中的特定点被命中。
我已经浏览了该站点上的许多帖子和网络上的示例,但是在我告诉线程等待后无法让网络服务器继续。一个基本的代码示例会很棒。
同步关键字是解决这个问题的正确方法吗?如果是这样,如何实现?我的应用程序的代码示例如下:
网络服务器
while (true) {
//block here until a connection request is made
socket = server_socket.accept();
try {
//create a new HTTPRequest object for every file request
HttpRequest request = new HttpRequest(socket, this);
//create a new thread for each request
Thread thread = new Thread(request);
//run the thread and have it return after complete
thread.run();
///////////////////////////////
wait here until notifed to proceed
///////////////////////////////
} catch (Exception e) {
e.printStackTrace(logFile);
}
}
线程代码
public void run() {
//code here
//notify web server to continue here
}
更新 - 最终代码如下。每当我发送响应标头时,HttpRequest 只会调用resumeListener.resume()(当然,还将接口添加为单独的类,并在HttpRequest 中添加addResumeListener(ResumeListener r1) 方法):
网络服务器部分
// server infinite loop
while (true) {
//block here until a connection request is made
socket = server_socket.accept();
try {
final Object locker = new Object();
//create a new HTTPRequest object for every file request
HttpRequest request = new HttpRequest(socket, this);
request.addResumeListener(new ResumeListener() {
public void resume() {
//get control of the lock and release the server
synchronized(locker) {
locker.notify();
}
}
});
synchronized(locker) {
//create a new thread for each request
Thread thread = new Thread(request);
//run the thread and have it return after complete
thread.start();
//tell this thread to wait until HttpRequest releases
//the server
locker.wait();
}
} catch (Exception e) {
e.printStackTrace(Session.logFile);
}
}
【问题讨论】:
-
作为一个学术问题,你为什么要编写自己的网络服务器代码?
-
该应用程序显示加密内容,因此基本上通过创建自己的内部网络服务器,我可以执行身份验证。如果外部浏览器尝试使用我传递数据的同一个套接字,那么如果请求来自我的应用程序,它将没有我内部提供的正确凭据。
-
我不明白这如何排除使用不同的网络服务器 - 几乎每个网络服务器都支持基于 IP 的身份验证,以及其他机制。
-
我无法争辩它是如何写的。我只是用 Java 重写了一个基于 .NET 的应用程序,这就是它当前的编码方式,并且在当前状态下非常安全。
-
问题是在编写网络服务器时很容易出错 - 例如,如果网络服务器对特别奇怪的请求的结束位置与沿途的某些代理有不同的想法,那么您可能会遇到有趣的安全问题。我强烈建议改用轻量级 servlet 容器...
标签: java multithreading synchronized