I'm developing a multithreaded web server for an android app and I've some problems with a page that uses an external .css file, and a .js file, but only with Google Chrome! With Firefox and Opera the page is rendered fine, with Google Chrome sometimes the .css is loaded, sometimes the .js, sometime both or neither.
This is my app's structure:
WebServer.java
class WebServer implements Runnable{
protected boolean ON;
public void start(){
if(!ON){
ON=true;
thread=new Thread(this,"WebServer");
thread.start(); }}
public void run(){
while(ON){
listenSocket = new ServerSocket(port);
Socket connectionSocket = listenSocket.accept();
Thread t = new Thread(new Client(connectionSocket));
t.start();
listenSocket.close();}
}}
Client.java
class Client implements Runnable {
public void start(){
thread=new Thread(this,"Client");
thread.start();}
public void run(){
//parse the request and send a file
}
}
myApp.java
public class myApp extends Activity{
onCreate(){
WebServer ws=new WebServer(8080);
}
onClick(){
...
ws.start();
}}
When I click a button on the activity, it call webserver.start(); In my opinion google chrome sends more requests concurrently and there's a problem with threads... Can you help me?
[EDIT] I had forgotten to write the loop in the run() method in the question
[EDIT 2] I just tried with an other pc, and there are problems also with firefox..
There is a general misunderstanding of the thread mechanism in your code.
A runnable has to override run. Not start. The run() method of the runnable will be called when the nesting thread will be started. In other words, the start method of your client will never be used, and hope fully, as it would create a thread inside a thread.. not very usefull.
Redesign your webser so that, :
then each client would, in it's run (no more start method) :
You could find some java code to inspire you on the web , some examples are well documented . Also, you could consider using java.nio package that is maybe less effective for a single request but much more effective at handling massive multiple connections. But code is harder.
You should consider reading more about runnables and also consider reading some stuff about synchronized key word to ensure that your web server doesn't start twice a connection for the same client or get confused in case of simultaneous requests.
Regards, Stéphane
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.