如何修复断开的管道socket异常(Java)?连接在哪里被关闭?
我正在为一个学校项目开发一个多线程web服务器。我应该能够进入浏览器上的本地主机,请求3个不同的文件(.htm、.jpeg、.pdf)。然而,当我这样做了一段时间。htm文件,其中包含图片(2个请求)。htm文件出现在浏览器中,但我尝试对图片进行的每次写入都会出现许多断管插座异常(分配要求一次写入1024字节)。我的实现方式显然有问题,但当我尝试为第二个文件编写时,我不知道连接在哪里被关闭
我尝试了几种不同的方法来解决这个问题,包括尝试读取socket输入流时的循环,但我认为这违背了多线程服务器的目的
服务器:
while(true){
try {
sock = servSock.accept(); // Handles the connection
// Connection received log
System.out.println("Connection received: " + new Date().toString() + " at " + sock.getInetAddress() + sock.getPort());
HTTP pro = new HTTP(sock); // Client handler
pro.run();
ServerThread serverThread = new ServerThread(pro);
// Starts ServerThread
serverThread.start();
} catch (Exception e){
System.out.println(e);
}
}
HTTP:
public void run(){
// Try to open reader
try{
readSock = new BufferedReader(new InputStreamReader(sock.getInputStream()));
} catch (Exception e){
System.out.println(e);
}
// Open output stream
try{
this.out = new DataOutputStream(sock.getOutputStream());
this.printOut = new PrintWriter(sock.getOutputStream());
} catch (Exception e){
System.out.println(e);
}
// Try to read incoming line
try {
this.reqMes = readSock.readLine();
} catch (IOException e) {
e.printStackTrace();
}
StringTokenizer st = new StringTokenizer(reqMes);
// Parse the request message
int count = 0;
while(st.hasMoreTokens()){
String str = st.nextToken();
if (count == 1){
this.fileName = "." + str;
}
count += 1;
}
System.out.println("File name received.");
File file = null;
try {
file = new File(this.fileName);
this.f = new FileInputStream(file); // File input stream
this.fileExists = true;
System.out.println("File " + this.fileName + " exists.");
} catch (FileNotFoundException e) {
System.out.println(e);
this.fileExists = false;
System.out.println("File does not exist.");
}
byte[] buffer = new byte[1024];
// Write status line
if (this.fileExists) {
System.out.println("Trying to write data");
try{
this.out.writeBytes("HTTP/1.0 " + "200 OK " + this.CRLF);
this.out.flush();
this.printOut.println("HTTP/1.0 " + "200 OK " + this.CRLF);
// Write Header
this.out.writeBytes("Content-type: " + getMime(this.fileName) + this.CRLF);
this.printOut.println("Content-type: " + getMime(this.fileName) + this.CRLF);
this.out.flush();
// Read file data
byte[] fileData = new byte[1024];
while (this.f.read(fileData) != -1) {
// Write File data
try{
this.out.write(fileData,0,1024);
this.out.flush(); // Flush output stream
} catch (IOException e) {
System.out.println(e);
}
}
System.out.println("Flushed");
} catch (IOException e) {
e.printStackTrace();
}
}
首先。htm文件在浏览器中,文件和html看起来很好。但它似乎又提出了第二个请求。html文件中的jpeg文件,浏览器无法加载java。网SocketException:每次写入数据时管道破裂(写入失败)
this.out.write(fileData,0,1024);
谢谢,非常感谢您的帮助
共 (0) 个答案