我需要項目通過Java中的套接字發送html文件。我設法讓文本出現在瀏覽器中,但沒有任何圖片加載。我發現這個代碼在線幫助我發送HTML文件,但我想知道是否有任何方式發送圖片。我有一個img
文件夾中的所有圖像,這是html
文件所在的位置。如何通過java中的套接字發送html文件及其圖像
public class SimpleFileServer {
public final static int SOCKET_PORT = 9000; // you may change this
public final static String FILE_TO_SEND = "D:\\Project 2\\index.html"; // you may change this
public static void main (String [] args) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
while (true) {
try {
sock = servsock.accept();
// send file
File myFile = new File (FILE_TO_SEND);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = sock.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
System.out.println("Done.");
} finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
}
} finally {
if (servsock != null) servsock.close();
}
}
}
html將到達瀏覽器,這將看到一個和瀏覽器將稍後在單獨的套接字上發出該URL的GET請求 – Exceptyon