在yg帮助下用Java做的,读取本地一张图片,发给浏览器(Client)
import javax.imageio.stream.FileImageInputStream;
import java.io.* ;
import java.net.* ;
public class Phttpd{
public static void main(String[] args) throws IOException{
ServerSocket servsock;
Socket sock ;
OutputStream out ;
BufferedReader in ;
FileInputStream infile = null;
byte[] buff = new byte[1024];
boolean cont;
int i ;
File file=new File("/Users/hwg/Desktop/大三上/EX2_NETWORK/web/a.html");
try{
servsock = new ServerSocket(8099);
while(true){
sock = servsock.accept();
try{
infile = new FileInputStream(file) ;
}
catch(FileNotFoundException e){
System.err.println("No found the file!!") ;
e.printStackTrace();
}
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out = sock.getOutputStream() ;
for(i=0;i<2;i++) {
System.out.println(in.readLine());
}
cont = true ;
//响应报文
out.write("http/1.1 200 OK\r\n".getBytes());
out.write("Content-Type: image/jpeg;\r\ncontent-length: 144759\r\n".getBytes());
out.write("\r\n".getBytes());
/**
* 写图片
*
*/
String img="/Users/hwg/Desktop/IMG_2111.jpeg";
FileInputStream fiis=new FileInputStream(new File(img));
int it=0;
while ((it=fiis.read(buff))!=-1){
out.write(buff);
}
out.flush();
fiis.close();
sock.close() ;
infile.close() ;
}
}catch(IOException e){
e.printStackTrace();
System.exit(1) ;
}
}
}