我這段代碼的目標是創建一個可以處理多個客戶端一個簡單的Web服務器,並且將與HTML迴應說「HI」,當客戶端請求它。
代碼:
這裏的測試號一個。它只能處理一個客戶端:
import java.net.*;
import java.io.*;
public class Webserver1 {
public static void main(String[] args) {
ServerSocket ss;
Socket s;
try {
//set up connection
ss = new ServerSocket(80);
s = ss.accept();
} catch (Exception e) {
System.out.println(e.getMessage());
return;
}
try (
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
DataOutputStream out = new DataOutputStream (s.getOutputStream());
) {
String inline = in.readLine();
//http request
if (inline.startsWith("GET")) {
//return http
out.writeBytes("<!doctype html><html><body><p>hi</p></body></html>");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
這裏是測試二號。它是爲了處理多個客戶端:
import java.net.*;
import java.io.*;
public class Webserver2 {
//class to handle connections
public static class server {
ServerSocket ss;
Socket s[] = new Socket[maxn];
public server() {
try {
ss = new ServerSocket(80);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public InputStream getis(int num) throws Exception {
return s[num].getInputStream();
}
public OutputStream getos(int num) throws Exception {
return s[num].getOutputStream();
}
public void close() throws Exception {
for (int i = 0; i < numc; i++) {
s[i].close();
}
}
public void newc() throws Exception {
s[numc + 1] = ss.accept();
}
}
static int numc = 0;
static final int maxn = 100;
static server se = new server();
public static void main(String[] args) {
try {
while (numc < 6) {
//set up connection, and start new thread
se.newc();
numc++;
System.out.println("0");
(new Client()).start();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static class Client extends Thread {
public void run() {
try(
BufferedReader in = new BufferedReader(new InputStreamReader(se.getis(numc)));
DataOutputStream out = new DataOutputStream (se.getos(numc));
) {
String inline;
while(true) {
inline = in.readLine();
//wait for http request
if (inline.startsWith("GET")) {
System.out.println("1");
//respond with header, and html
out.writeBytes("HTTP/1.1 200 OK\r\n");
out.writeBytes("Connection: close\r\n");
out.writeBytes("Content-Type: text/html\r\n\r\n");
out.writeBytes("<!doctype html><html><body><p>hi</p></body></html>");
out.flush();
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}
問題:
在我的電腦,如果我跑的第一個例子,並且在我的瀏覽器I型:「http://192.168.1.xxx」,我得到一個簡單的「喜」。但是,如果我嘗試同樣的事情,那麼在第二個方面它根本行不通。但是如果在命令提示符下輸入:telnet 192.168.1.xxx 80,那麼輸入GET就會返回html。另外,如果我用PrintWriter替換DataOutputStream,它甚至不會將它發送到telnet。但是,我知道它會嘗試,因爲每次連接時程序打印「0」,每次打印時打印「1」。
問題:
那是什麼阻止瀏覽器查看HTML的問題?
它是否與html本身,我設置我的連接或DataOutputStream的方式?
我該如何解決這個問題?
大於6000 ...這是非常隨機的,如果他能夠在他的電腦上工作80,端口不是問題。 – 2015-03-25 05:55:45
感謝您的回答!新的和改進的代碼很好。原來問題是我在發送html之後需要關閉套接字,瀏覽器認爲我還在發送信息 – Evan 2015-03-26 16:45:36