您的位置:首页 > 理论基础 > 计算机网络

用Java套接字创建HTTP客户与服务器程序

2017-02-11 23:16 411 查看
服务器端代码如下:

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 套接字 Java-Web