---restore content starts---
Points:
1. Simply respond to a GET request and return the local lena.jpg to the client
2. Use the most basic socket programming
3. Thread management Using thread pooling
4. Read the lena.jpg into memory to reduce the number of IO
5.MyHttpServer as a server class, serverthread as a service processing thread class
1. Join the thread pool
Executorservice pool = Executors.newfixedthreadpool (maxclientnums);
2. Client Access opens the service thread and joins it to the thread pool
while (true) {try {Socket client=server.accept (); if (client.isconnected ()) {Pool.submit (new Serverthread (client)); Use Subit to join thread pool}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}
3. Analog HTTP response returned to the client
OutputStream Out=client.getoutputstream (); BufferedWriter bf=new BufferedWriter (New OutputStreamWriter (out, "UTF-8")); String headstring= "http/1.1 ok\r\n"; String serverstring= "connection:keep-alive\r\n"; String typestring= "content-type:image/png\r\n"; String lenstring= "content-length:" +myhttpserver.len+ "\ r \ n"; String endstring= "\ r \ n"; Bf.write (headstring); Bf.write (serverstring); Bf.write (typestring); Bf.write (lenstring); Bf.write (endstring); Bf.flush (); Note Flush
4. Write a picture to the cache
Set static variables
Static File file=new file ("f:\\java\\code\\myhttpserver\\lena.jpg"); Static bytearrayoutputstream bout; Static byte []b; Static int Len;
Write a picture to the Byte[]b store
bin=NewBufferedinputstream (Newfileinputstream (file)); //write lena.jpg to cachelen=bin.available (); Bout=NewBytearrayoutputstream (); intlength; bytetemp[]=New byte[1024]; while((Length=bin.read (temp))!=-1) {bout.write (temp,0, length); } b=New byte[Len]; b=bout.tobytearray ();
5. Return the picture to the client
Out.write (MYHTTPSERVER.B); Out.flush (); Out.close (); MyHttpServer.bin.close ();
Source: Http://pan.baidu.com/s/1o8wO70Y
(The code that is written for the job to be met ....) )
---restore content ends---
Java thread pool socket implements simple HTTP server