I'm having a problem with a Java SocketServer, i'm building a very basic Java handled Web Server.
So i'm creating a socket server, this is the code from the run method as i have made the server threaded.
The problem i'm having is that the server code seems to freeze as while((line = reader.readLine()) != null)
until the remote client closes the connection. I'm using the chrome plugin ARC (Advanced REST Client) to do the testing with.
public void start() throws ServerException{
this.running = true;
try{
this.server = new ServerSocket(this.port);
}catch(IOException ex){
System.err.println("Failed to create Server Port is inuse!");
throw new ServerException("Unable to bind to port '" + this.port + "'", ex);
}
while(!isStopped()){
Socket client = null;
try{
client = this.server.accept();
}catch(IOException ex){
if(isStopped()) {
return;
}
throw new ServerException("Error accepting client connection", ex);
}
new Thread(
new ServerWorker(client, this)
).start();
}
}
This is the ServerWorker
public void run(){
try {
InputStream input = clientSocket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
OutputStream output = clientSocket.getOutputStream();
long time = System.currentTimeMillis();
ArrayList<String> lines = new ArrayList<String>();
String line;
while((line = reader.readLine()) != null){
lines.add(line);
}
String[] msg = new String[lines.size()];
msg = lines.toArray(msg);
output.write("HTTP/1.1 200
".getBytes());
output.write("
".getBytes());
new HandleConnection(msg).begin(output);
reader.close();
output.close();
System.out.println("Request processed: " + time);
} catch (IOException e) {
}
}
and finally this is the handler:
public void begin(OutputStream output){
for(int i = 0; i < lines.length; i++){
System.out.println(lines[i]);
}
try{
output.write("{"Response":"Ok"}
".getBytes());
}catch(IOException e){}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…