62,621
社区成员
发帖
与我相关
我的任务
分享
public class SimpleHttpServerIO {
private ServerSocketChannel serverSocketChannel;
private Charset charset = Charset.forName("UTF-8");
public SimpleHttpServerIO() throws IOException {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(80));
System.out.println("服务器启动。。。。。");
}
public void service() {
while (true) {
SocketChannel channel = null;
try {
channel = serverSocketChannel.accept();
System.out.println("收到来自客户端的连接:" + channel.getRemoteAddress());
StringBuffer sb = new StringBuffer("HTTP/1.1 200 OK\r\n");
sb.append("Content-Type:text/html\r\n\r\n");
channel.write(charset.encode(sb.toString()));
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);
buffer.flip();
String str = charset.decode(buffer).toString();
FileInputStream in;
if (str.indexOf("\r\n") != -1) {
str = str.substring(0, str.indexOf("\r\n"));
if (str.indexOf("login.htm") != -1) {
in = new FileInputStream(
"D:\\workspace\\Socket\\src\\test5\\login.htm");
} else {
in = new FileInputStream(
"D:\\workspace\\Socket\\src\\test5\\index.htm");
}
FileChannel fileChannel = in.getChannel();
fileChannel.transferTo(0, fileChannel.size(), channel);
}
channel.close();
} catch (Exception e) {
e.printStackTrace();
} finally{
if(channel != null){
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String args[]) throws IOException {
new SimpleHttpServerIO().service();
}
}
多谢提醒。。
看到了3次请求,1次是空的,浏览器怎么会发这么一条请求呢?
[/quote]
1.浏览器会发favicon.ico的访问,这个自己判断一下过滤就可以了;
2.3次请求,你看一下,客户端发起就几次?服务端收到了几次?会不会是你服务端的缓冲池太小了?
多谢提醒。。
看到了3次请求,1次是空的,浏览器怎么会发这么一条请求呢?