java练习小项目 tomcat服务器

这个项目是一个用编写的服务器的程序,主要是学习java的基本知识,例如多线程编程、java网络编程。

功能是服务器端提供服务,客户端提交url请求,服务器端返回相应的资源并记录客户端提交的信息。github连接,喜欢的朋友记得star喔

运行的结果如图:

这里模仿了浏览器向服务器请求html资源,服务器根据相应的url返回了相应html文件。

服务器端的运行结果为:

 本示完成了服务器的基本功能,但是相对简陋,对于java学习和理解服务器的运行方式有着很大的帮助

 

主要的构架为:

 

废话不说,代码如下;

GetPosyTest.java:

 

package tomcatServer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class GetPosyTest {

	public  static  String  sendGet(String  url,String  pram) throws IOException{
		URL realurl = new  URL(url);
		URLConnection conn = realurl.openConnection();
		conn.setRequestProperty("accept", "*/*");
		conn.setRequestProperty("connection", "Keep-Alive");
		conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"+ "; SV1)");
		conn.connect();
		Map<String, List<String>> map = conn.getHeaderFields();
		for(String i:map.keySet()){
			System.out.println("状态为"+map.get(i));
		}
		InputStream input = conn.getInputStream();
		BufferedReader in = new  BufferedReader(new  InputStreamReader(input,"utf-8"));
		String line;

		while((line=in.readLine())!=null){
			System.out.println(line);
		}
		return null;
	}
	
	
	public  static  String  sendPost(String  url,String  pram) throws IOException{
		URL realurl = new  URL(url);
		URLConnection conn = realurl.openConnection();
		conn.setRequestProperty("accept", "*/*");
		conn.setRequestProperty("connection", "Keep-Alive");
		conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"+ "; SV1)");
		conn.setDoOutput(true);
		conn.setDoInput(true);
		PrintWriter  out=new  PrintWriter(conn.getOutputStream());
		
		out.print(pram);
		out.flush();
		
		

		InputStream input = conn.getInputStream();
		Map<String, List<String>> map = conn.getHeaderFields();
		for(String i:map.keySet()){
			System.out.println("状态为"+map.get(i));
		}
		BufferedReader in = new  BufferedReader(new  InputStreamReader(input,"utf-8"));
		String line;

		while((line=in.readLine())!=null){
			System.out.println(line);
		}
	
		return null;
	}
	
	
	
	
	
	public static void main(String[] args) throws IOException {
		long startTime = System.currentTimeMillis();    //获取开始时间
		for(int  i=0;i<2;i++){
		//发送get请求
		String s = GetPosyTest.sendGet("http://localhost:8882/login.html", null);
		//发送post请求
		String s1 = GetPosyTest.sendPost("http://localhost:8882/login.html", "name=123&age=223");
		}
		long endTime = System.currentTimeMillis();    //获取结束时间
		System.out.println("程序运行时间:" + (endTime - startTime) + "ms");    //输出程序运行时间
//		程序运行时间:17353ms  10
//		程序运行时间:15754ms  100
//		程序运行时间:13996ms  20
//		程序运行时间:11683ms  30
	}
}

Request.java

package tomcatServer;


import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;



public class Request {

	private  Socket  client;
	private  String  url;
	private  String  method;
	private  String protocal;
	Request(Socket  client) throws IOException{
		this.client=client;		
		BufferedReader br=new  BufferedReader(new  InputStreamReader(client.getInputStream()));
		String line1=br.readLine();
		System.out.println("客户端提交的基本信息:"+line1);
		String[] fields = line1.split(" ");
		method=fields[0];
		url=fields[1];
		protocal=fields[2];
		if(method.equalsIgnoreCase("get")){
			if(url.contains("?")){
				String[] tmp=url.split("[?]");
				url=tmp[0];
				String property=tmp[1];
			
			}
		}else{
			int length = 0;
			while(br.ready()){
				String line = br.readLine();
				if (line.contains("Content-Length")) {
					String[] split2 = line.split(" ");
					length = Integer.parseInt(split2[1]);
				}
				if(line.equals("")){
					break;
				}
			}
			String info = null;
			char[] ch = new char[length];
			br.read(ch, 0, length);
			info = new String(ch, 0, length);
			String[] prams = info.split("&");
			System.out.println("提交到服务器信息为:");
			for(String pram_:prams){
				System.out.println(pram_);
			}
		}
		
	}
	public Socket getClient() {
		return client;
	}
	public void setClient(Socket client) {
		this.client = client;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getMethod() {
		return method;
	}
	public void setMethod(String method) {
		this.method = method;
	}
	public String getProtocal() {
		return protocal;
	}
	public void setProtocal(String protocal) {
		this.protocal = protocal;
	}
	public static  void  main(String[]  args) throws IOException{
	    ServerSocket server = new  ServerSocket(8880);
	    Socket sc = server.accept();
		new  Request(sc);
	}
}

Response.java

package tomcatServer;


import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;



public class  Response{
	
	private  static String path;
	private  PrintStream  ps;
	private  Socket  client;
	
	Response(Socket  client_) throws IOException{
		this.client=client_;
		ps=new  PrintStream(client.getOutputStream());
	}
	public void  read() throws IOException{

		FileInputStream fis = null;
		try {
			fis = new FileInputStream(new File(path));
			ps.println("HTTP/1.1 200 OK");
			ps.println();
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = fis.read(buf)) != -1) {
				ps.write(buf, 0, len);
				ps.flush();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
        }finally{
        	if(ps!=null){
        		ps.close();
        	}else if(fis!=null){
        		fis.close();
        	}else if(client!=null){
        		System.out.println("执行到了吗");
        		client.close();
        	}
        }
	}
	public void read(String  url) throws IOException{
		if(url.equalsIgnoreCase("/")){
			this.path="E:\\download\\Java-master\\tomcatServer3.0\\src\\source\\2.jpg";
		}else{
			this.path="E:/download/Java-master/tomcatServer3.0/src/source"+url;
			System.out.println("客户端请求文件所在地址:"+path);
		}
		File  file=new  File(path);
		if(!file.exists()){
			path="E:\\download\\Java-master\\tomcatServer3.0\\src\\source\\error.html";
		}
		read();
    }
	
	public static  void  main(String[]  args) throws IOException{
	    ServerSocket server = new  ServerSocket(8880);
	    Socket sc = server.accept();
		Response rs = new  Response(sc);
		rs.read();
	}
}

这里html资源的位置需要看你的自己的路径而定

Server.java

package tomcatServer;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
	private static Properties  prop;
	private static int   port;
	private ServerSocket server;
	Server(){
		prop=new Properties();
	    try {
			prop.load(new  FileInputStream(new  File("E:/download/Java-master/tomcatServer3.0/src/source/property.properties")));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    String porttmp=prop.getProperty("port");
	    this.port=Integer.parseInt(porttmp);
	}
	public void  provideServer() throws IOException, InterruptedException{
		System.out.println("开始监听的端口为:"+port);
		this.server = new  ServerSocket(port);
		ExecutorService pool = Executors.newFixedThreadPool(30);
	    while(true){
			  Socket client= server.accept();
			  ServerThread mythread = new  ServerThread(client);
			  pool.execute(mythread);
			 
	    }
	}
	
	
	public  static  void  main(String[]  args) throws IOException, InterruptedException{
	  
		 Server  server=new Server();
		 server.provideServer();
		 
//		 GetPosyTest.sendPost("http://localhost:8882/login.html", "name=123&age=223");
	}
	
}

ServerThread.java

package tomcatServer;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;





public class ServerThread extends  Thread {

	private  Socket  client;
	ServerThread(Socket  client){
		this.client=client;
	}
	@Override
	public  void  run(){
		try {
			Response  response=new  Response(client);
			Request  request=new  Request(client);
			response.read(request.getUrl());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		                                                                                                                                                                                                                                            
		
	}
	
	public  static  void  main(String[]  args) throws IOException, InterruptedException{
		  ServerSocket server = new  ServerSocket(8881);
		 
		  while(true){
			  Socket sc = server.accept();
			  ServerThread mythread = new  ServerThread(sc);
			  mythread.start();
			  mythread.join();
		  }
		 
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java EE(Java Enterprise Edition)是一种用于开发企业级应用程序的Java平台。它包含了一系列的规范和API,提供了强大的功能和工具来简化和加快企业级应用程序的开发过程。 在准备Java EE考试的复习资料时,有几个关键的方面需要重点关注。首先是了解Java EE的体系结构,包括各个层次组件的功能和关系。这包括Web层、业务逻辑层和持久化层等。理解这些概念对于构建稳健的企业级应用程序非常重要。 其次,需要学习掌握Java EE的核心技术和API,如Servlet、JSP、EJB、JPA等。这些技术和API是Java EE的基础,掌握它们能够帮助开发人员设计和实现高效的应用程序。 此外,了解Java EE的安全机制和容器管理是考试中的重要内容。熟悉如何配置和使用应用服务器(如Tomcat、JBoss等)可以提高应用程序的性能和安全性。 在复习资料的准备过程中,可以参考一些权威的教材和指南,如《Java EE开发权威指南》和《Java EE 企业级开发教程》等。这些资料通常包含了详细的知识点和实践案例,能够帮助理解Java EE的概念和应用。 最后,为了更好地准备考试,可以尝试做一些实际的项练习。通过实践,可以将理论知识应用于实际开发中,加深对Java EE的理解和掌握。 总之,复习Java EE考试需要掌握Java EE的体系结构、核心技术和API、安全机制和容器管理等相关知识。通过准备专业的教材和指南,并进行实际项练习,可以更好地备考Java EE考试。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值