用Java套接字创建HTTP客户与服务器程序
2017-02-11 23:16
411 查看
服务器端代码如下:
客户端代码如下:
hello1.html代码如下:
服务器端的输出:
客户端输出:
当然除了用自己写的Client访问自己写的Server,也能用浏览器:
服务器这边的输出结果如下:
同样你也能用自己写的Client访问Tomcat,上面Client类的代码做两处改动即可(uri和端口号):
返回的html比较长,就不贴了。
至于为什么,因为它们都遵守HTTP协议。
package com.company; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { int port; port = 8081; ServerSocket serverSocket; try { serverSocket = new ServerSocket(port); System.out.println("server is listening port:" + serverSocket.getLocalPort()); while (true) { Socket socket = serverSocket.accept(); System.out.println("build a link with client:" + socket.getInetAddress() + ":" + socket.getPort()); InputStream socketInputStream = socket.getInputStream(); //等待HTTP请求 try { Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } byte[] buffer = new byte[socketInputStream.available()]; socketInputStream.read(buffer); String request = new String(buffer); System.out.println(request); String firstLineOfRequest = request.substring(0, request.indexOf("\r\n")); String[] firstLineParts = firstLineOfRequest.split(" "); String uri = firstLineParts[1]; //意思意思的写了几个 String contentType; if (uri.contains(".html") || uri.contains(".htm")) { contentType = "text/html"; } else { if (uri.contains(".jpg") || uri.contains(".jpeg")) { contentType = "image/jpeg"; } else { contentType = "application/octet-stream"; } } //response result String responseFirstLine = "HTTP/1.1 200 OK\r\n"; String responseHeader = "Content-Type:" + contentType + "\r\n\r\n"; InputStream inputStream = new FileInputStream("D:\\Study\\" + "Java\\IDEA_Projects\\IdeaProjects\\src\\com\\company\\" + uri); OutputStream outputStream = socket.getOutputStream(); outputStream.write(responseFirstLine.getBytes()); outputStream.write(responseHeader.getBytes()); int len = 0; byte[] bytes = new byte[1024]; while ((len = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } //等待客户接受HTTP响应结果 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } socket.close(); } } catch (IOException e) { e.printStackTrace(); } } }
客户端代码如下:
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; public class Client { public static void main(String[] args) { // String uri = "/index.jsp"; String uri = "hello1.html"; Socket socket = null; try { socket = new Socket("localhost",8081); StringBuffer stringBuffer = new StringBuffer("GET " + uri + " HTTP/1.1\r\n"); //意思意思的写了几个 stringBuffer.append("Accept: */*\r\n"); stringBuffer.append("Accept-Language: zh-cn\r\n"); stringBuffer.append("Accept-Encoding: gzip, deflate\r\n"); stringBuffer.append("Host: localhost:8080\r\n"); stringBuffer.append("Connection: Keep-Alive\r\n\r\n"); OutputStream outputStream = socket.getOutputStream(); System.out.println(stringBuffer.toString()); outputStream.write(stringBuffer.toString().getBytes()); //等待服务器的响应结果 try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } InputStream inputStream = socket.getInputStream(); byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes); System.out.println(new String(bytes)); } catch (IOException e) { e.printStackTrace(); } finally { try { if (socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
hello1.html代码如下:
<html> <head> <title>Hello World!</title> </head> <body> <h1>Hello</h1> <p>cvdshjcbnddjsnc cbjdsncdjsncjsdnc cdjsmcdksncjedn</p> </body> </html>
服务器端的输出:
server is listening port:8081 build a link with client:/127.0.0.1:62760 GET hello1.html HTTP/1.1 Accept: */* Accept-Language: zh-cn Accept-Encoding: gzip, deflate Host: localhost:8081 Connection: Keep-Alive
客户端输出:
HTTP/1.1 200 OK
Content-Type:text/html
<html> <head> <title>Hello World!</title> </head> <body> <h1>Hello</h1> <p>cvdshjcbnddjsnc cbjdsncdjsncjsdnc cdjsmcdksncjedn</p> </body> </html>
当然除了用自己写的Client访问自己写的Server,也能用浏览器:
http://localhost:8081/hello1.html
服务器这边的输出结果如下:
server is listening port:8081 build a link with client:/0:0:0:0:0:0:0:1:49733 GET /hello1.html HTTP/1.1 Host: localhost:8081 Connection: keep-alive Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4
同样你也能用自己写的Client访问Tomcat,上面Client类的代码做两处改动即可(uri和端口号):
String uri = "/index.jsp"; socket = new Socket("localhost",8080);
返回的html比较长,就不贴了。
至于为什么,因为它们都遵守HTTP协议。
相关文章推荐
- JAVA套接字创建HTTP客户与服务器程序
- HTTP头部详解及使用Java套接字处理HTTP请求
- automation服务器不能创建对象”的问题的解决方案总结大全(转载于javasee【http://bigtree2006.javaeye.com/blog/321383】)
- IntelliJ IDEA 12 创建Web项目 教程 超详细版--http://www.cnblogs.com/cnjava/archive/2013/01/29/2881654.html
- Java开发学习笔记之三:HTTP客户请求数据格式
- java创建http接口,及调用
- java创建http接口
- java—实现一个监听器HttpServletRequest的创建销毁、在线人数 (56)
- 在Eclipse中创建JSP文件时,Can not find the tag library descriptor for "http://java.sun.com/jsf/html"
- HTTP头部详解及使用Java套接字处理HTTP请求
- flex基础篇一,基于httpservice通信+java后台的项目创建
- Java乔晓松-ajax的概述和XMLHTTPRequest对象的创建过程
- java使用http创建https连接,并且使用http实现webservice服务端
- nginx源代码分析--监听套接字的创建 套接字的监听 HTTP请求创建连接
- HTTP头部详解及使用Java套接字处理HTTP请求
- Java的XML创建、解析文档(转载自http://blog.csdn.net/psyuhen/article/details/7539228)
- nginx源码分析--监听套接字的创建 套接字的监听 HTTP请求创建连接
- JAVA环境下创建JSP文件报错: The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Pa