网络编程及三大协议(TCP + UDP + Http)

一、网络编程

1.计算机网络

2.网络编程

3.网络编程三要素

4.InetAddress – 主机类

import java.net.InetAddress;
import java.net.UnknownHostException;

public class Test01 {

	public static void main(String[] args) throws UnknownHostException {
		
		//获取到指定域名的服务器IP地址
//		InetAddress byName = InetAddress.getByName("www.baidu.com");
//  	System.out.println(byName);//14.215.177.39
	
		//获取到指定域名的所有服务器 IPd地址
//		InetAddress[] allByName = InetAddress.getAllByName("www.baidu.com");
//		for (InetAddress inetAddress : allByName) {
//			System.out.println(inetAddress);
//		}
		
		//获取到本机的IP地址
		InetAddress localHost = InetAddress.getLocalHost();
		System.out.println(localHost);
	}
}

二、TCP协议

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

//客户端
public class Client {
	//注意:关闭流等于关闭Socket
	public static void main(String[] args) throws UnknownHostException, IOException {
		
		//武松
		Socket socket = new Socket("127.0.0.001", 8888);
		
		//1.向服务端发送消息
		PrintStream ps = new PrintStream(socket.getOutputStream());
		ps.println("武松:小二,上好酒好菜!");
		
		//4.接收来自服务端的消息
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
		String readLine = br.readLine();
		System.out.println(readLine);
		
		//关闭资源
		ps.close();
		br.close();
		socket.close();
	}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
//服务端
public class Server {

	public static void main(String[] args) throws IOException {
		
		//客栈掌柜
		ServerSocket server = new ServerSocket(8888);
		
		System.out.println("等待端连接中...");
		
	
		//店小二
		//accept()是线程阻塞的方法,客户端和服务端连接成功后才会生成一个Socket对象
		Socket socket = server.accept();
		
		System.out.println("欢迎光临,客人来了~~~");
		
		//2.接收来自客户端的消息
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK"));
		String readLine = br.readLine();
		System.out.println(readLine);
		
		//3.向客户端发送消息
		PrintStream ps = new PrintStream(socket.getOutputStream());
		ps.println("店小二:好的,您请坐!");
		
		//关闭资源
		br.close();
		ps.close();
		socket.close();
		server.close();
	}
}

1.TCP案例之 传输文件

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket socket = new Socket("127.0.0.002", 6666);
		
		//客户端读取源文件,通过Socket提供的输出流向服务端传输数据即可
		
		FileInputStream fis = new FileInputStream("测试视频.mp4");
		OutputStream os = socket.getOutputStream();
		
		byte[] b = new byte[1024];
		int len;
		while ((len = fis.read(b)) != -1) {
			os.write(b, 0, len);
		}
		fis.close();
		os.close();
		socket.close();
	}
}
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	public static void main(String[] args) throws IOException {
		
		ServerSocket server = new ServerSocket(6666);
		Socket socket = server.accept();
		
		//通过Socket提供过的输入流接收来自客户端的数据,并写入到本地文件中
		InputStream is = socket.getInputStream();
		FileOutputStream fos = new FileOutputStream("copy.mp4");
		
		byte[] b = new byte[1024];
		int len;
		while ((len = is.read(b)) != -1) {
			fos.write(b, 0, len);
		}
		
		is.close();
		fos.close();
		socket.close();
		server.close();
	}
}

2.TCP协议 之 一对一聊天

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {

	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket socket = new Socket("127.0.0.001", 5555);
		
		Scanner scan = new Scanner(System.in);
		
		PrintStream ps = new PrintStream(socket.getOutputStream());
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK"));
		
		while (true) {
			
			ps.println("小小:" + scan.next());
			
			String readLine = br.readLine();
			System.out.println(readLine);
		}
		
	}
}

3.TCP协议 之 优化一对一聊天

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {

	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket socket = new Socket("127.0.0.1",5010);
		
		new ReceiveThread(socket).start();
		
		Scanner scan = new Scanner(System.in);
		PrintStream ps = new PrintStream(socket.getOutputStream());
		
		while (true) {
			ps.println("刘备:" + scan.next());
		}
	}
}
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {

	public static void main(String[] args) throws IOException {
		
		ServerSocket server = new ServerSocket(5010);
		
		Socket socket = server.accept();
		
		new ReceiveThread(socket).start();
		
		Scanner scan = new Scanner(System.in);
		PrintStream ps = new PrintStream(socket.getOutputStream());
		
		while (true) {
			ps.println("张飞:" + scan.next());
		}
	}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class ReceiveThread extends Thread{

	private Socket socket;

	public ReceiveThread(Socket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
			while (true) {
				String readLine = br.readLine();
				System.out.println(readLine);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

4.TCP协议 之 群聊

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {

	public static void main(String[] args) throws UnknownHostException, IOException {
		
		Socket socket = new Socket("127.0.0.1", 4563);
		
		new ReceiveThread(socket).start();
		
		Scanner scan = new Scanner(System.in);
		PrintStream ps = new PrintStream(socket.getOutputStream());
		while (true) {
			ps.println("关羽:" + scan.next());
		}
	}
}

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;

public class Server {

	public static final ConcurrentHashMap<String, Socket> map = new ConcurrentHashMap<>();
	
	public static void main(String[] args) throws IOException {
		
		ServerSocket server = new ServerSocket(4563);
		
		while (true) {
			
			Socket socket = server.accept();
			
			//获取客户端的IP地址
			String ip = socket.getInetAddress().toString();
			System.out.println(ip);
			
			//将IP地址和Socket对象存入Map中
			map.put(ip,socket);
			
			//此线程 -- 接收当前Socket的消息,并发送给其他Socket
			 new ServerThread(socket).start();
		}
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class ReceiveThread extends Thread{

	private  Socket socket;

	public ReceiveThread(Socket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {

		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK"));
			while (true) {
				String readLine = br.readLine();
				System.out.println(readLine);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class ServerThread extends Thread{

	private Socket socket;

	public ServerThread(Socket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {
		//接收当前Socket的消息,并发送给其他Socket
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK"));
			
			while (true) {
				String readLine = br.readLine();
				System.out.println(readLine);
				
				ConcurrentHashMap<String, Socket> map = Server.map;
				Set<Entry<String,Socket>> entrySet = map.entrySet();
				for (Entry<String, Socket> entry : entrySet) {
					String ip = entry.getKey();
					Socket value = entry.getValue();
					
					if (!socket.getInetAddress().toString().equals(ip)) {
						PrintStream ps = new PrintStream(value.getOutputStream());
						ps.println(readLine);
					}
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}

四、UDP协议

1.简介

import java.net.DatagramSocket;
import java.net.SocketException;

public class Client01 {

	public static void main(String[] args) throws SocketException {
		
		DatagramSocket socket = new DatagramSocket(8808);
		
		new ReceiveThread(socket).start();
		
		new SendThread(socket, "127.0.0.1", 9099, "马超").start();
		
	}
}

import java.net.DatagramSocket;
import java.net.SocketException;

public class Client02 {

	public static void main(String[] args) throws SocketException {
		
		DatagramSocket socket = new DatagramSocket(9099);
		
		new ReceiveThread(socket).start();
		new SendThread(socket, "127.0.0.1", 8808, "吕布").start();
	}
}

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class ReceiveThread extends Thread{

	private DatagramSocket socket;

	public ReceiveThread(DatagramSocket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {

		while (true) {
		
			try {
				//数据容器
				byte[] buf = new byte[1024];
				//数据报包
				DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);
				//接收数据报包
				socket.receive(dp);
				//打印
				System.out.println(new String(buf).trim());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class SendThread extends Thread{

	private DatagramSocket socket;
    private String ip;
    private int port;
    private String name;
    
    public SendThread(DatagramSocket socket, String ip, int port, String name) {
		this.socket = socket;
		this.ip = ip;
		this.port = port;
		this.name = name;
	}

	@Override
    public void run() {
		
		Scanner scan = new Scanner(System.in);
		
		while (true) {
			
			try {
				//数据
				byte[] buf = (name + ":" + scan.next()).getBytes();
				//数据报包
				DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);
				//发送数据报包
				socket.send(dp);
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    }
}

2.TCP VS UDP

五、Http协议

1.Http案例之获取来电归属地

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class Test01 {

	public static void main(String[] args) throws IOException {
		
		//获取链接地址
		URL url = new URL("https://cx.shouji.360.cn/phonearea.php?number=15879090133");
		//获取连接对象
		HttpsURLConnection huc = (HttpsURLConnection) url.openConnection();
		
		//设置参数
		//设置请求方式
		huc.setRequestMethod("GET");
		//允许使用输入流
		huc.setDoInput(true);
		//允许使用输出流
		huc.setDoOutput(true);
		//设置连接超时时间
		huc.setConnectTimeout(5000);
		//设置读取超时时间
		huc.setReadTimeout(5200);
		
		//获取响应状态码
		int responseCode = huc.getResponseCode();
		
		if (responseCode == HttpsURLConnection.HTTP_OK) {//响应成功
			
			InputStreamReader isr = new InputStreamReader(huc.getInputStream(), "UTF-8");
			char[] c = new char[1024];
			int len;
			while ((len = isr.read(c)) != -1) {
				System.out.println(new String(c, 0, len));
			}
			isr.close();
		}else if(responseCode == HttpsURLConnection.HTTP_NOT_FOUND){
			System.out.println("报错了 --- 页面未找到");
		}
	}
}


2.Http案例之获取快递

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class test02 {

	public static void main(String[] args) throws IOException {
		
		//获取地址
		URL url = new URL("https://www.kuaidi100.com/?type=zhongtong&postid=78624759493002");
		
		//获取连接对象
		HttpsURLConnection huc = (HttpsURLConnection) url.openConnection();
		
		//设置参数
		//设置请求方式
		huc.setRequestMethod("GET");
		//允许使用输入流
		huc.setDoInput(true);
		//允许使用输出流
		huc.setDoOutput(true);
		//设置连接超时时间
		huc.setConnectTimeout(5200);
		//设置读取超时时间
		huc.setReadTimeout(5000);
		
		//获取响应状态码
		int responseCode = huc.getResponseCode();
		
		if (responseCode == HttpsURLConnection.HTTP_OK) {//响应成功
			
			InputStreamReader isr = new InputStreamReader(huc.getInputStream(),"UTF-8");
			
			char[] c = new char[1024];
			int len;
			while ((len = isr.read(c)) != -1) {
				System.out.println(new String(c, 0, len));
			}
			isr.close();
		} else if(responseCode == HttpsURLConnection.HTTP_NOT_FOUND){
			System.out.println("报错了 --- 页面未找到");
		}
	}
}

3.Http案例之下载图片

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class Test03 {

	public static void main(String[] args) throws IOException {
		
		//获取连接地址
		URL url = new URL("https://ts1.cn.mm.bing.net/th/id/R-C.f27d775447d9f4ab7c71bbe5f8e38831?rik=4ISLL%2fsQWoSY8g&riu=http%3a%2f%2fimg95.699pic.com%2fphoto%2f40014%2f9369.jpg_wh860.jpg&ehk=S%2bDyu%2bhUKhk%2foLxQ6D7fO350Z%2fkmlDrRz5sM5J1QrCk%3d&risl=&pid=ImgRaw&r=0");
		
		//获取连接对象
		HttpsURLConnection huc = (HttpsURLConnection) url.openConnection();
		
		//设置参数
		//设置请求方式
		huc.setRequestMethod("GET");
		//允许使用输入流
		huc.setDoInput(true);
		//允许使用输出流
		huc.setDoOutput(true);
		//设置连接超时时间
		huc.setConnectTimeout(5200);
		//设置读取超时时间
		huc.setReadTimeout(5000);
		
		
		//获取响应状态码
		int responseCode = huc.getResponseCode();
		
		if (responseCode == HttpsURLConnection.HTTP_OK) {
			
			InputStream is = huc.getInputStream();
			FileOutputStream fos = new FileOutputStream("冲击的力量.jpg");
			
			byte[] b = new byte[1024];
			int len;
			while ((len = is.read(b)) != -1) {
				fos.write(b, 0, len);
			}
			is.close();
			fos.close();
		}else if (responseCode == HttpsURLConnection.HTTP_NOT_FOUND) {
			System.out.println("报错了 --- 页面未找到");
		}
		
	}
}

11-03 18:12