【发布时间】:2016-10-09 23:01:02
【问题描述】:
我遇到了 Java SocketServer 的问题,我正在构建一个非常基本的 Java 处理的 Web 服务器。
所以我正在创建一个套接字服务器,这是来自 run 方法的代码,因为我已经使服务器线程化。
我遇到的问题是服务器代码似乎冻结为while((line = reader.readLine()) != null),直到远程客户端关闭连接。我正在使用 chrome 插件 ARC(高级 REST 客户端)进行测试。
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();
}
}
这是 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\r\n".getBytes());
output.write("\r\n".getBytes());
new HandleConnection(msg).begin(output);
reader.close();
output.close();
System.out.println("Request processed: " + time);
} catch (IOException e) {
}
}
最后这是处理程序:
public void begin(OutputStream output){
for(int i = 0; i < lines.length; i++){
System.out.println(lines[i]);
}
try{
output.write("{\"Response\":\"Ok\"}\r\n".getBytes());
}catch(IOException e){}
}
【问题讨论】:
-
修正了你非常不正确的标题。
-
@EJP 抱歉,因为我正在调试并发现错误,我更改了问题内容并忘记更改标题。
标签: java sockets http tcp bufferedreader