客户端
package com.jvm.t1; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; public class TCPClient { public static void main(String[] args) throws IOException { //创建套接字 Socket socket = new Socket("127.0.0.1", 8888); //创建输出流 OutputStream outputStream = socket.getOutputStream(); //写数据 outputStream.write("你好啊,服务器".getBytes()); //释放资源 socket.close(); } }
服务器
package com.jvm.t1; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class TCPServer { public static void main(String[] args) throws IOException { //创建服务器套接字 ServerSocket serverSocket = new ServerSocket(8888); //获取发出请求的客户端套接字 Socket accept = serverSocket.accept(); InputStream inputStream = accept.getInputStream(); byte []bytes = new byte[1024]; int len = inputStream.read(bytes); System.out.println(new String(bytes,0,len)); accept.close(); serverSocket.close(); } }
进阶版:
客户端发送数据,服务器端显示客户端的数据,并向客户端发出响应数据
客户端:
package com.tcp; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; public class TCPClient { public static void main(String[] args) throws IOException { //创建套接字 Socket socket = new Socket("127.0.0.1", 8888); //创建输出流 OutputStream outputStream = socket.getOutputStream(); //写数据 outputStream.write("你好啊,服务器".getBytes()); //接收服务器端的数据 InputStream inputStream = socket.getInputStream(); byte []bytes = new byte[1024]; int len = inputStream.read(bytes); System.out.println("接收来自服务器端的数据:"+new String(bytes,0,len)); //释放资源 socket.close(); } }
服务器端:
package com.tcp; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class TCPServer { public static void main(String[] args) throws IOException { //创建服务器套接字 ServerSocket serverSocket = new ServerSocket(8888); //获取发出请求的客户端套接字 Socket accept = serverSocket.accept(); //接收来自客户端的数据 InputStream inputStream = accept.getInputStream(); byte []bytes = new byte[1024]; int len = inputStream.read(bytes); System.out.println("来自客户端的消息:"+ new String(bytes,0,len)); //向客户端发送数据 OutputStream outputStream = accept.getOutputStream(); outputStream.write("你好啊,客户端!,消息已收到".getBytes()); //关闭 accept.close(); serverSocket.close(); } }练习2
客户端:数据来自于键盘录入,直到输入的数据是886,发送数据结束
服务器:接收到的数据在控制台输出
客户端
package com.jvm.t1; import java.io.*; import java.net.Socket; public class TCPClient { public static void main(String[] args) throws IOException { //创建套接字 Socket socket = new Socket("127.0.0.1", 8888); //字符流转换成字节流,再封装成缓冲流 BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); String line; while((line = bufferedReader.readLine()) != null){ if("886".equals(line)) break; bufferedWriter.write(line); bufferedWriter.newline(); //换行 bufferedWriter.flush(); //刷新 } //释放资源 socket.close(); } }
服务器端
package com.jvm.t1; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class TCPServer { public static void main(String[] args) throws IOException { //创建服务器套接字 ServerSocket serverSocket = new ServerSocket(8888); //获取发出请求的客户端套接字 Socket accept = serverSocket.accept(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(accept.getInputStream())); String line; while((line = bufferedReader.readLine()) != null){ System.out.println(line); } accept.close(); serverSocket.close(); } }
此时,在浏览器输入url,观看打印台的内容
修改服务器端
package com.jvm.t1; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class TCPServer { public static void main(String[] args) throws IOException { //创建服务器套接字 ServerSocket serverSocket = new ServerSocket(8888); while (true){ //获取发出请求的客户端套接字 Socket accept = serverSocket.accept(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream())); bufferedWriter.write("HTTP/1.1 200 OK"); bufferedWriter.newline(); bufferedWriter.write("Content-Type:text/html"); bufferedWriter.newline(); bufferedWriter.write("Content-Length:20"); bufferedWriter.newline(); bufferedWriter.newline(); bufferedWriter.write("Hello,World!abcdefg"); bufferedWriter.flush(); accept.close(); } } }
先学习
2阶——Http协议(Request封装请求、Response封装输出) 路径的写法
手写服务器httpserver_封装Response_封装Request_JAVA199-201
浏览器输入以下url:
GET /index?name=hangover&password=123 HTTP/1.1 Host: localhost:8888 Connection: keep-alive Cache-Control: max-age=0 sec-ch-ua: "Chromium";v="94", "Google Chrome";v="94", ";Not A Brand";v="99" sec-ch-ua-mobile: ?0 sec-ch-ua-platform: "Windows" Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,**;q=0.8,application/signed-exchange;v=b3;q=0.9 Sec-Fetch-Site: same-site Sec-Fetch-Mode: navigate Sec-Fetch-User: ?1 Sec-Fetch-Dest: document Referer: http://localhost:63342/ Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh;q=0.9 cookie: Idea-17670b7a=4d792870-1d4b-4f1f-8740-811ab0ac3cdc; Idea-10a747c5=921e4f0b-61d8-41f2-9041-499eea091075; Pycharm-34408c98=77b79e3b-a685-4ad8-bdd1-9a409381a7e9 name=shmily&password=123456 Process finished with exit code 0封装Request
package com.jvm.t1; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.*; //对请求报文进行封装 public class Request { private String method; //请求方式 private String URI; //请求资源 private Map> parameterMapValue;//请求参数 public static final String CRLF = "rn"; private InputStream inputStream; private String requestInfo; //用来保存请求报文数据 public Request() { method = ""; URI = ""; parameterMapValue = new HashMap<>(); requestInfo = ""; } public Request(InputStream inputStream) { this(); this.inputStream = inputStream; try{ byte []data = new byte[2048]; int len = inputStream.read(data); requestInfo = new String(data,0,len); }catch (IOException e){ return; } parseRequestInfo(); } public String getMethod() { return method; } public String getUrl() { return URI; } public Map > getParameterMapValue() { return parameterMapValue; } //根据参数名称获取对应的多个值 public String[] getParameters(String parameter){ List values = null; if((values = parameterMapValue.get(parameter)) == null){ return null; }else{ return values.toArray(new String[0]); } } //根据参数名称获取对应的单个值 public String getParameter(String parameter){ String[] values = getParameters(parameter); if(values == null) return null; return values[0]; } //分析请求信息 private void parseRequestInfo(){ if((null == requestInfo) || (requestInfo = requestInfo.trim()).equals("")) return; String paramString = "";//接收请求参数 //获取请求方式 //首部行 GET /index?name=hangover&password=123 HTTP/1.1 String firstLine = requestInfo.substring(0,requestInfo.indexOf(CRLF)); int idx = requestInfo.indexOf("/"); // /的位置 this.method = firstLine.substring(0,idx).trim(); String urlStr = firstLine.substring(idx,firstLine.indexOf("HTTP")).trim(); // POST /index HTTP/1.1 if(this.method.equals("POST")){ this.URI = urlStr; paramString = requestInfo.substring(requestInfo.lastIndexOf(CRLF)).trim(); }else if(this.method.equals("GET")){ //考虑没有参数 if(urlStr.contains("?")){ String []urlArray = urlStr.split("\?"); this.URI = urlArray[0]; paramString = urlArray[1]; }else{ this.URI = urlStr; } } parseParams(paramString); } //将请求参数封装到Map中 // name=shmily&password=123456 private void parseParams(String paramString){ //分割,将字符串转成数组 StringTokenizer stringTokenizer = new StringTokenizer(paramString, "&"); while (stringTokenizer.hasMoreTokens()){ String keyValue = stringTokenizer.nextToken(); String[] keyValues = keyValue.split("="); //考虑name=shmily&password if(keyValues.length == 1){ keyValues = Arrays.copyOf(keyValues,2); //申请两个空间,并复制原来的 keyValues[1] = null; } String key = keyValues[0].trim(); String value = null == keyValues[1] ?null:decode(keyValues[1].trim(),"utf-8"); //考虑name=shmily&name=hangover if(!parameterMapValue.containsKey(key)){ parameterMapValue.put(key,new ArrayList<>()); } List values = parameterMapValue.get(key); values.add(value); } } //解决中文 private String decode(String value,String code){ try{ return java.net.URLDecoder.decode(value,code); }catch (UnsupportedEncodingException e){ e.printStackTrace(); } return null; } }
服务器端
package com.jvm.t1; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class TCPServer { public static void main(String[] args) throws IOException { //创建服务器套接字 ServerSocket serverSocket = new ServerSocket(8888); //获取发出请求的客户端套接字 Socket accept = serverSocket.accept(); InputStream inputStream = accept.getInputStream(); Request request = new Request(inputStream); System.out.println("请求方式:" + request.getMethod()); System.out.println("请求资源:"+request.getUrl()); System.out.println("姓名:"+request.getParameter("name")); System.out.println("密码:"+request.getParameter("password")); accept.close(); serverSocket.close(); } }封装Response
package com.jvm.t1; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.security.cert.CRL; import java.util.Date; //封装响应报文 public class Response { public static final String CRLF = "tn"; public static final String BLANK = " "; //输出流 private BufferedWriter bufferedWriter; //响应头 private StringBuilder headInfo; //响应体 private StringBuilder content; //响应体长度 private int len = 0; //响应类型 private String contentType = "text/html;charset=utf-8"; public Response() { headInfo = new StringBuilder(); content = new StringBuilder(); len = 0; } public Response(OutputStream outputStream){ this(); bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream)); } public void setContentType(String contentType) { this.contentType = contentType; } //构建响应头 private void createHeadInfo(int code){ //构建状态行 HTTP协议版本,状态代码,描述 headInfo.append("HTTP/1.1").append(BLANK).append(code).append(BLANK); switch (code){ case 200: headInfo.append("OK"); break; case 404: headInfo.append("Not Found"); break; case 500: headInfo.append("Server Error"); break; } headInfo.append(CRLF); //响应头 headInfo.append("Server:test Server/0.0.1").append(CRLF); headInfo.append("Date").append(new Date()).append(CRLF); headInfo.append("Content-type:").append(contentType).append(CRLF); //正文长度 headInfo.append("Content-Length:").append(len); headInfo.append("nn"); } //构建响应体 public Response print(String info){ content.append(info); len += info.length(); return this; } //构建响应体+回车 public Response println(String info){ content.append(info).append(CRLF); len += (info + CRLF).getBytes().length; return this; } //推送到客户端 public void pushToClient(int code) throws IOException{ createHeadInfo(code); bufferedWriter.append(headInfo.toString()); bufferedWriter.append(content.toString()); bufferedWriter.flush(); bufferedWriter.close(); } }
服务器端
package com.jvm.t1; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class TCPServer { public static void main(String[] args) throws IOException { //创建服务器套接字 ServerSocket serverSocket = new ServerSocket(8888); while (true){ //获取发出请求的客户端套接字 Socket accept = serverSocket.accept(); InputStream inputStream = accept.getInputStream(); Request request = new Request(inputStream); System.out.println("请求方式:" + request.getMethod()); System.out.println("请求资源:"+request.getUrl()); System.out.println("姓名:"+request.getParameter("name")); System.out.println("密码:"+request.getParameter("password")); OutputStream outputStream = accept.getOutputStream(); Response response = new Response(outputStream); response.println("HTTP响应示例 "); response.println(""); response.println("欢迎:").println(request.getParameter("name")).println("回来"); response.println(""); response.pushToClient(200); accept.close(); } } }
一个简单的Servlet容器实现
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)