我正在製作一個簡單的Web服務器,每次客戶端連接時都會產生一個新線程。然後我需要使用BufferedOutputStream發送響應(因爲HTTP協議在行尾需要一個/ r/n)。 這裏是我的代碼:使用傳遞給線程的套接字時,「套接字已關閉」異常?
class HttpServer{
public static void main(String args[]){
ServerSocket ss = null;
int port = 40000;
try{
if(args.length > 0){
port = Integer.parseInt(args[0]);
}
ss = new ServerSocket(port);
while(true){
Socket client = ss.accept();
User user = new User(client);
user.start();
}
}
catch(Exception e){
System.err.println(e.getMessage());
}
}
}
我的用戶等級:
class User extends Thread{
Socket client;
public User(Socket s){
client = s;
}
public void run(){
try{
BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream());
println(bos, "Hello World");
bos.close();
client.close();
}
catch(Exception e){
System.err.println(e.getMessage());
}
}
private void println(BufferedOutputStream bos, String s) throws IOException {
String news = s + "\r\n";
byte[] array = news.getBytes();
for(int i=0; i<array.length; i++){
bos.write(array[i]);
}
return;
}
}
當我嘗試創建的BufferedOutputStream出現的問題;它給了我一個「套接字已關閉」的錯誤,我不知道爲什麼。
任何幫助將不勝感激。
謝謝!
這是不起作用的代碼:
class User extends Thread{
Socket client;
public User(Socket s){
client = s;
}
public void run(){
try{
System.out.println("Address: " + client.getInetAddress().toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line;
Boolean first = true;
while(!((line = reader.readLine()).equals(""))){
if(first)
System.out.println(line.split(" ")[1]);
first = false;
}
reader.close();
BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream());
println(bos, "Hello World");
bos.close();
// Close socket
client.close();
}
catch(Exception e){
System.err.println(e.getMessage());
}
}
private void println(BufferedOutputStream bos, String s) throws IOException {
String news = s + "\r\n";
byte[] array = news.getBytes();
for(int i=0; i<array.length; i++){
bos.write(array[i]);
}
return;
}
}
很奇怪,我不知道發生了什麼 – tbodt
客戶端如何調用您的服務器?也許客戶在從服務器讀取任何輸出之前關閉連接? – tangens
我一直在瀏覽器中輸入localhost:40000進行測試,這就是結果。我也嘗試使用本地地址,例如192.168.0.100:40000具有相同的結果。 – Neurion