http://127.0.0.1:8000/webserver/web/index.html
项目名:webserver
资源名目录: /web
返回hello
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| package web.server;
import java.io.*; import java.net.ServerSocket; import java.net.Socket;
public class TCPServer { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(8000); Socket accept = server.accept();
InputStream clientIS = accept.getInputStream();
clientIS.read();
OutputStream outputStream = accept.getOutputStream(); outputStream.write("HTTP/1.1 200 OK\r\n".getBytes()); outputStream.write("Content-Type:text/html\r\n".getBytes()); outputStream.write("\r\n".getBytes()); outputStream.write("hello".getBytes()); accept.close(); server.close();
} }
|
返回html
浏览器解析服务器回写的html页面中,如果有图片,那么浏览器会单独开一个线程,读取服务器的图片
所以必须使服务无线循环 不能单次服务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| package file.upload;
import java.io.*; import java.net.ServerSocket; import java.net.Socket;
public class FileUploadServer { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(8000); while(true){ Socket accept = server.accept(); new Thread(new Runnable() { @Override public void run() { try{ InputStream inputStream = accept.getInputStream(); File file = new File("D:\\upload"); if(!file.exists()){ file.mkdirs(); } FileOutputStream fileOutputStream = new FileOutputStream(file +"\\"+System.currentTimeMillis()+".gif"); int len = 0; byte[] bytes = new byte[1024 * 10]; while ((len = inputStream.read(bytes)) != -1) { fileOutputStream.write(bytes, 0, len); }
accept.getOutputStream().write("接收完毕".getBytes()); fileOutputStream.close();
}catch (IOException e){ e.printStackTrace(); }finally { try { accept.close(); }catch (IOException e){ e.printStackTrace(); } }
} });
}
} }
|
最后更新时间:
各位大爷们,评论在下最方,打赏点下面。转载请注明GitHub项目地址:https://github.com/wordfeng/wordfeng.github.io