这个项目是一个用编写的服务器的程序,主要是学习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();
}
}
}