⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 webserver.java

📁 java 服务器程序。。。。即webserver
💻 JAVA
字号:
import java.net.*;
import java.io.*;


/**A class to implement a web server.*/
public class WebServer {
	public static void main(String argv[]) throws Exception
	{
		
		String sRcvMsg;
		String[] sModifiedMsg;
		String fileName;
		int i = 0;
		
		ServerSocket serverSocket = new ServerSocket(6789);//Establish a socket for communication.
		Socket listenerSocket = serverSocket.accept();//Establish a listener to accept request.
		
		BufferedReader inFromClient = new BufferedReader(new InputStreamReader(listenerSocket.getInputStream()));
		DataOutputStream outToClient = new DataOutputStream(listenerSocket.getOutputStream());
		
	    sRcvMsg = inFromClient.readLine();//Read message from client.
	    System.out.println(sRcvMsg);
		sModifiedMsg = sRcvMsg.split("\\s");
		
		
		//Indicate what type the message is.
		if (sModifiedMsg[0].equals("GET"))
		{
			fileName = sModifiedMsg[++i];
			fileName = fileName.substring(1);
			
			File file = new File(fileName);
			int numOfBytes = (int) file.length();
			FileInputStream inFile = new FileInputStream(fileName);
			byte[] fileInBytes = new byte[numOfBytes];
			
			inFile.read(fileInBytes);//Read contents of the file.
			outToClient.writeBytes("HTTP/1.0 200 Document Follows\r\n");//Announce the web server is ready.
			
			//See what type of the document is.
			if (fileName.endsWith(".jpg"))
			{
				outToClient.writeBytes("Content-Type:image/jpeg\r\n");
			}
			
			if (fileName.endsWith(".gif"))
			{
				outToClient.writeBytes("Content-Type:image/gif\r\n");
			}
			
			//Display the length of the file.
			outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n");
			outToClient.writeBytes("\r\n");
			
			outToClient.write(fileInBytes, 0, numOfBytes);
			
			//Close connection when finishing transferring file.
			listenerSocket.close();
		}
		else
		{
			System.out.println("Bad Request Message.");
		}
		
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -