package WebServer;
import java.io.*;
import java.util.*;
import java.net.*;
final public class WebServer {
ServerSocket server;
public void start()throws Exception{
server=new ServerSocket(5000);
Socket client;
while(true){
client=server.accept();
Thread t1=new Thread(new Handlehttp(client));
t1.start();
}
}
public static void main(String[] args) {
try{
new WebServer().start();
}catch(Exception e){
e.printStackTrace();
}
}
}
final class Handlehttp implements Runnable{
Socket s;
DataOutputStream ds;
BufferedReader br;
public Handlehttp(Socket s) throws Exception {
this.s=s;
ds=new DataOutputStream(s.getOutputStream());
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
}
private synchronized void httprequest()throws Exception{
String rqln,var;
rqln=br.readLine();
System.out.println("Port number : "+s.getPort());
if(rqln!=null)
System.out.println(rqln);
while((var=br.readLine())!=null){
System.out.println(var);
}
}
private synchronized void httpreponse()throws Exception{
String var,fileName;
fileName="D:/file.htm";
FileInputStream fis=new FileInputStream(fileName);
int var1;
var="HTTP/1.0 200 OK\r\n";
var=var+"Connection: keep-alive\r\n";
var=var+"Server : First\r\n";
var=var+"Content-Type: text/html\r\n";
var=var+"\r\n";
ds.writeBytes(var);
while((var1=fis.read())!=-1){
ds.write(var1);
}
}
@Override
public void run() {
try{
httprequest();
httpreponse();
//s.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
我在ds.writeBytes上得到一個套接字軟件錯誤沒有其他異常發生我猜Socket是closed.I能夠看到HTTP請求從瀏覽器,但仍然沒有運氣打印任何排序信息瀏覽器套接字寫入錯誤
BTW我沒有做出關於多線程服務器,但由於以前的問題都已經解決了(可能被解決)已經開始新課題來回套接字錯誤前一個問題
我得到的例外是
Port number : 10225
GET /file.htm HTTP/1.1
Host: localhost:5000
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36
DNT: 1
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Port number : 10226
java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStream.java:132)
at java.io.DataOutputStream.writeBytes(DataOutputStream.java:276)
at WebServer.Handlehttp.httpreponse(WebServer.java:57)
at WebServer.Handlehttp.run(WebServer.java:82)
at java.lang.Thread.run(Thread.java:722)
請發佈客戶端代碼。 – Jiji
當您運行應用程序併發出http請求時,您獲得的輸出是什麼? – ahmedalkaff
@Jiji服務器應該發送來自瀏覽器的請求的HTTP響應 – AAB