public class WebServer { //服务端Socket只要一个,所以定义成static, 同一时间只能一个线程访问(主线程) private static ServerSocket ss; public static void main(String[] args) throws IOException { //绑定端口,只会执行一次 ss = new ServerSocket(8999); //远端服务器使用ServerSocket技术打开一个端口,等待请求的到来
//主线程永远不死,所以用了个死循环 while (true) { //这是一个IO阻塞式语句,也就是如果没有请求(IO操作)进来,当前线程会在此等待,不再向下执行 Socket socket = ss.accept(); // socket:(本机IP+ 本机端口 +服务端IP+ 服务端端口,用来唯一标示一条TCP联接)通道
//得到请求报文(内容) StringBuffer sb = new StringBuffer(); PrintWriter pw = null; try { InputStream socketIn = socket.getInputStream(); //从通道socket上获得流 BufferedReader br = new BufferedReader(new InputStreamReader(socketIn)); while(true) { String msg = br.readLine(); sb.append(msg); System.out.println(msg); if (msg == null || msg.trim().equals("")) { break; } } //输入响应报文 pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); // 所发送HTTP数据包
pw.println("HTTP/1.1 200 OK"); pw.println("Content-Type: text/html;charset=UTF-8"); pw.println(); pw.write("html"); pw.flush(); } catch (IOException exception) { //TODO 处理异常 } finally { socket.close(); pw.close(); //socket = null; } } } }
servlet 是单例的 只初始化一次
可以在Web.xml中配置
<init-param> <param-name></param-name> <param-value></param-value> </init-param>
然后在servlet的init函数中获得参数
config.getInitParameter();
publicclass WebServer {
//服务端Socket只要一个,所以定义成static, 同一时间只能一个线程访问(主线程)
privatestatic ServerSocket ss;
publicstaticvoid main(String[] args) throws IOException {
//绑定端口,只会执行一次
ss = new ServerSocket(8999);
//主线程永远不死,所以用了个死循环
while (true) {
//这是一个IO阻塞式语句,也就是如果没有请求(IO操作)进来,当前线程会在此等待,不再向下执行
Socket socket = ss.accept();
//得到请求报文(内容)
StringBuffer sb = new StringBuffer();
PrintWriter pw = null;
try {
InputStream socketIn = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(socketIn));
while(true) {
String msg = br.readLine();
sb.append(msg);
System.out.println(msg);
if (msg == null || msg.trim().equals("")) {
break;
}
}
//输入响应报文
pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
pw.println("HTTP/1.1 200 OK");
pw.println("Content-Type: text/html;charset=UTF-8");
pw.println();
pw.write("html");
pw.flush();
} catch (IOException exception) {
//TODO处理异常
} finally {
socket.close();
pw.close();
//socket = null;
}
}
}
}