---恢复内容开始---
要点:
1.只需回应Get请求,将本地的lena.jpg返回给客户端
2.使用最基本的socket编程
3.使用线程池进行线程管理
4.将lena.jpg读入内存中,减少IO次数
5.MyHttpServer作为服务器类,ServerThread作为服务处理线程类
1.加入线程池
ExecutorService pool = Executors.newFixedThreadPool(MaxClientNums);
2.有客户访问则开启服务线程并将其加入线程池
while(true){ try { Socket client=server.accept(); if(client.isConnected()){ pool.submit(new ServerThread(client)); //利用subit加入线程池 } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
3.模拟Http回应返回给客户端
OutputStream out=client.getOutputStream(); BufferedWriter bf=new BufferedWriter(new OutputStreamWriter(out,"UTF-8")); String headString="HTTP/1.1 200 OK "; String serverString="Connection: Keep-Alive "; String typeString="Content-Type: image/png "; String lenString="Content-Length:"+MyHttpServer.len+" "; String endString=" "; bf.write(headString); bf.write(serverString); bf.write(typeString); bf.write(lenString); bf.write(endString); bf.flush(); //注意flush
4.将图片写入缓存
设置静态变量
static File file=new File("F:\java\code\MyHttpServer\lena.jpg"); static ByteArrayOutputStream bout; static byte[]b; static int len;
将图片写入byte[]b中存储
bin=new BufferedInputStream(new FileInputStream(file)); //将lena.jpg写入缓存 len=bin.available(); bout=new ByteArrayOutputStream(); int length; byte temp[]=new byte[1024]; while((length=bin.read(temp))!=-1){ bout.write(temp, 0, length); } b=new byte[len]; b=bout.toByteArray();
5.将图片返回给客户端
out.write(MyHttpServer.b); out.flush(); out.close(); MyHttpServer.bin.close();
源码: http://pan.baidu.com/s/1o8wO70Y
(应付作业写的代码。。。。)
---恢复内容结束---