1.TCP/IP协议
TCP 传输控制协议
IP 网络地址协议
协议共分为以下四层:应用层、传输层、互联网层、网络访问层
应用层协议
FTP 文件传输协议
http 超文本传输协议(访问网页)
telnet 远程登录
ssh 远程登录(保证安全)
DNS(域名系统)
传输层协议
打包和确定目的应用程序
TCP(保障数据的可靠有序), UDP (不保证数据的可靠有序)
互联网层
ip协议
网络访问层
2.HTTP协议
位于应用层
1).请求 请求方式 资源地址 协议版本 请求首部字段
eg:
GET /index/heml HTTP/1.1
Host: localhost
2)响应 协议版本 状态码 状态码的原因短语 响应首部字段
eg:
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 20
Date: Sat, 24 Nov 2018 01:37:25 GMT
Nov 24 2018 09:37:25
3.客户端编程
1)使用Socket
创建Socket
Socket socket = new Socket("ip地址“,端口号);
发数据
socket.getOutputStream();
收数据
socket.getInputStream();
public class TestSocket {
public static void main(String[] args) throws IOException {
// 1. 新建Socket对象
// host: 主机ip地址 port:端口号
Socket socket = new Socket("127.0.0.1", 5000);
// 2. 发送数据用输出流
OutputStream out = socket.getOutputStream();
out.write("GET /index.html HTTP/1.1\n".getBytes());
out.write("Host: localhost\n".getBytes());
out.write("\n".getBytes());
out.write("\n".getBytes());
// 3. 接收响应用输入流
InputStream in = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
while(true) {
String line = reader.readLine();
if(line == null) {
break;
}
System.out.println(line);
}
socket.close();
}
}
2)使用URL
创建 new URL("http://ip地址:端口/资源地址")
建立连接, 发送get请求 HTTPURLConnection conn = url.openConnection();
接收数据 conn.getInputStream();
public class TestURL {
public static void main(String[] args) throws IOException {
HttpURLConnection connection = (HttpURLConnection)
new URL("http://192.168.3.123:80/img/chrome.png").openConnection();
InputStream in = connection.getInputStream();
FileOutputStream image = new FileOutputStream("e:\\1.png");
while(true) {
byte[] buf = new byte[1024*8];
int len = in.read(buf);
if(len == -1) {
break;
}
image.write(buf, 0, len);
}
image.close();
connection.disconnect();
}
}
4.服务器端编程
服务器端编程步骤
此程序一次只能响应一个客户端
public class testSeverSocket {
public static void main(String[] args) throws IOException {
//1.创建serverSocket
ServerSocket serverSocket = new ServerSocket(5000);
//2.调用accept 等待客户端连接
Socket accept = serverSocket.accept();
InputStream in = accept.getInputStream();
OutputStream out = accept.getOutputStream();
byte[] bt = new byte[1024];
while(true){
//3.接收客户的输入
int len=in.read(bt);
if(len==-1)
break;
//4. 拿到输出流向客户写入
out.write(bt,0,len);
}
}
}
加入多线程后就可以响应多个客户端
public class ThreadServerSocket {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5000);
while(true){
Socket accept = serverSocket.accept();
new Thread(()->{
try {
control(accept);
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
private static void control(Socket accept) throws IOException {
InputStream in = accept.getInputStream();
OutputStream out = accept.getOutputStream();
byte[] bt = new byte[1024];
while(true){
int len=in.read(bt);
if(len==-1)
break;
out.write(bt,0,len);
}
}
}